/**
 * 场景操作的相关方法
 */
var baseURL = localStorage.getItem("baseURL");
//获取地址参数函数
function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  //unescape() 函数可对通过 escape() 编码的字符串进行解码。
  //通过找到形式为 %xx 和 %uxxxx 的字符序列（x 表示十六进制的数字），用 Unicode 字符 \u00xx 和 \uxxxx 替换这样的字符序列进行解码
  //ECMAScript v3 已从标准中删除了 unescape() 函数，并反对使用它，因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
  if (r != null) {
    //console.log(decodeURI(r[2]));
    return decodeURI(r[2]); //返回参数值
  } else {
    return null;
  }
};

//基本信息图纸值，图纸是否已显示变量
var hasShow = false;
//基本信息图纸值，检测鼠标是否悬浮与组件避免移动时误触发
var isOver = false;

window.onunload = function() {
  clearInterval();
};

! function(win) {
  "use strict";
  var StageView = function() {
    this.writeValue = '';
    this.scaling = 0; //画面缩放比例，存在这里是因为滚轮时要从新计算画布移动数据。
    this.stageMove = true; //没有网页，摄像头，视频，天气，echart才可以滚轮
  }
  StageView.prototype = {
    constructor: StageView,
    /**
     * 初始化场景（预览）
     */
    initStage: function(stageJson) {

      var stage = Konva.Node.create(stageJson, 'container');
      var layer = stage.getLayers()[1];
      //设置容器的大小
      // $("#container").height(stage.height());
      //$("#container").width(stage.width());

      this.stage = stage;
      this.layer = layer;
      var stage_move = this.UnDrag(); //没有网页，摄像头，视频，echart，天气才允许滚轮
      this.stageMove = stage_move; //没有网页，摄像头，视频，天气，echart才可以滚轮
      this.adaptPhoneWindows();

    },
    /**
     * 初始化场景（客户端查看）
     */
    initClientStage: function(stage_id) {
      var stageType = getUrlParam('type');
      var stageObjJson = "";
      if (stageType != "dialog") {
        stageObjJson = eval("initConfig." + initjson.clientViewbackFunction + "('" + stage_id + "')");
      } else {
        stageObjJson = localStorage.getItem("stageObjJson") ? localStorage.getItem("stageObjJson") : '';
      }
      var stage = Konva.Node.create(stageObjJson, 'container');
      var layer = stage.getLayers()[1];
      //设置容器的大小
      // $("#container").height(stage.height());
      //$("#container").width(stage.width());

      this.stage = stage;
      this.layer = layer;
      var stage_move = this.UnDrag(); //没有网页，摄像头，视频，echart，天气才允许滚轮
      this.stageMove = stage_move; //没有网页，摄像头，视频，天气，echart才可以滚轮
      this.adaptPhoneWindows();
    },
    /**
     * 设置div背景
     */
    setDivBackground: function() {

      var layer_background = this.stage.findOne('.layer_grid'); // 获取背景图层
      var urlImage = layer_background.attrs.backgroundImageURL;
      if (urlImage != '' && typeof(urlImage) != "undefined") {
        $("#stageBackground").css({
          "background": "url('" + urlImage + "') no-repeat center center",
          "background-size": "100% 100%"
        });
        var nodes = layer_background.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        var layer_background = this.stage.findOne('.layer_background');
        layer_background.visible(false);
        this.stage.draw();
      } else {
        var layer_background = this.stage.findOne('.layer_background');
        var colort = layer_background.fill();
        layer_background.visible(false);
        $("#stageBackground").css('background', colort);
        this.stage.draw();
      }


    },

    /**
     * 设置背景图层的图片（背景不铺满）
     */
    setStageBackground: function(backgroundLayer) {
      var stageWidth = this.stage.width();
      var stageHeight = this.stage.height();
      var urlImage = backgroundLayer.attrs.backgroundImageURL;
      if (typeof(urlImage) != "undefined" && urlImage != "") {
        //删除原有的 image 组件。
        var nodes = backgroundLayer.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        Konva.Image.fromURL(urlImage, function(imageNode) {
          imageNode.name("myShapeBackgroundImage");
          imageNode.width(stageWidth);
          imageNode.height(stageHeight);
          backgroundLayer.add(imageNode);
          //moduleObject.draw();
          backgroundLayer.draw();
        }, "config/gyyj/noimg.svg");
      }
    },
    /**
     * 自适应手机和电脑
     */
    adaptPhoneWindows: function() {
      var stageType = getUrlParam('type');
      //滑入弹出图纸对话框
      var mouseDialog = Number(localStorage.getItem("mouseDialog"));
      console.log(stageType);
      //画面平移需要参数
      var iframeWindow = $("#container").parent(); //窗口大小
      var windowWidth = iframeWindow.width(); //窗口宽
      var windowHeight = iframeWindow.height(); //窗口高

      //fatherHeight用于滑入弹出图纸对话框的判断
      localStorage.setItem("fatherHeight", windowHeight);
      if (stageType != "dialog") {
        localStorage.setItem("viewHeight", windowHeight);
      }

      var canvasDiv = $("#container"); //画布
      var canvasWidth = canvasDiv.width(); //画布宽
      var canvasHeight = canvasDiv.height(); //画布高
      if (stageType == "dialog") {
        //弹出窗口的大小其实就是修正后的图纸大小，不含标题栏
        windowWidth = Number(localStorage.getItem("newWidth"));
        windowHeight = Number(localStorage.getItem("newHeight"));
      }
      if (mouseDialog) {
        //弹出窗口的大小其实就是修正后的图纸大小，不含标题栏
        windowWidth = Number(localStorage.getItem("mouseWidth"));
        windowHeight = Number(localStorage.getItem("mouseHeight"));
      }

      //还原上次对画布的所有设置 starat--------------------------------------------
      if (typeof(this.stage_height_original) != "undefined") {
        $("#container").height(""); //设置宽高=空，下面恢复stage原始状态的时候会自动设置
        $("#container").width("");
        // 恢复stage原始状态
        this.stage.width(this.stage_width_original);
        this.stage.height(this.stage_height_original);
        this.stage.scale({
          x: 1,
          y: 1
        });
        var stageRotation = this.stage.rotation();
        this.stage.rotate(-stageRotation);
        this.stage.setAttr("offset", {
          x: 0,
          y: 0
        });
        this.stage.draw();
        //拿到还原后的画布宽高
        canvasDiv = $("#container"); //画布
        canvasWidth = canvasDiv.width(); //画布宽
        canvasHeight = canvasDiv.height(); //画布高



        // 恢复s container 下 画布div 原始状态
        $('#container').css({
          'top': 0,
          'left': 0
        });
        var defaultRotateStage_Func = "rotateZ(0deg)";
        $('#container .konvajs-content').css({
          "transform": defaultRotateStage_Func, //缩放比例
          "transform-origin": "left top", //缩放基点

          "-ms-transform": defaultRotateStage_Func,
          "-ms-transform-origin": "left top",

          "-moz-transform": defaultRotateStage_Func,
          "-moz-transform-origin": "left top",

          "-webkit-transform": defaultRotateStage_Func,
          "-webkit-transform-origin": "left top",

          "-o-transform": defaultRotateStage_Func,
          "-o-transform-origin": "left top",

          "top": 0,

          // height:this.stage_height_original,//不要特意设置容器div的匡高，改属性有画布自动去决定
          //width:this.stage_width_original
        });

        // 恢复 container 原始状态
        var defaultRotateFunc = "rotateZ(0deg) scale(1,1)";
        $('#container').css({
          "transform": defaultRotateFunc, //缩放比例
          "-ms-transform": defaultRotateFunc,
          "-moz-transform": defaultRotateFunc,
          "-webkit-transform": defaultRotateFunc,
          "-o-transform": defaultRotateFunc,
        });

        //恢复背景设置
        var defaultStageBackground_Func = "rotateZ(0deg)";
        $('#stageBackground').css({
          "transform": defaultStageBackground_Func, //缩放比例
          "transform-origin": "left top", //缩放基点
          "-ms-transform": defaultStageBackground_Func,
          /* IE 9 */
          "-ms-transform-origin": "left top",
          "-moz-transform": defaultStageBackground_Func,
          /* Firefox */
          "-moz-transform-origin": "left top",
          "-webkit-transform": defaultStageBackground_Func,
          /* Safari 和 Chrome */
          "-webkit-transform-origin": "left top",
          "-o-transform": defaultStageBackground_Func,
          /* Opera */
          "-o-transform-origin": "left top",
          "left": 0,
          "height": '100%',
          "width": '100%'
        });
      }
      //还原上次对画布的所有设置 end----------------------------------------------------------------------------


      //保存场景的原始实际宽度和高度
      if (typeof(this.stage_height_original) == "undefined") {
        this.stage_height_original = canvasHeight;
        this.stage_width_original = canvasWidth;
      }

      var stageParent = $("#container").parent();
      var windowWidth_t = windowWidth;
      var windowHeight_t = windowHeight;
      var rotateS = 0;
      if (windowHeight_t > windowWidth_t && this.stage_height_original < this
        .stage_width_original) { //屏幕的高大于宽，且，实际画面的高小于宽 才需要旋转

        //this.stage.draggable(true);
        var tempsize = windowHeight_t;
        //宽高颠倒
        windowHeight_t = windowWidth_t;
        windowWidth_t = tempsize;
        rotateS = 90;
        this.isRotate = true;


      } else {
        //this.stage.draggable(true);
        this.isRotate = false;
        rotateS = 0;



      }
      //计算放大百分比，电脑端
      //var heightDiff=windowHeight_t-this.stage_height_original;
      //var multiplying_power  = heightDiff/this.stage_height_original;
      var heightDiff = 0;
      var widthDiff = 0;
      var multiplying_power = 0;
      //不是两边同时超出视口的情况下,缩小
      // if(!(this.stage_height_original>windowHeight_t && this.stage_width_original>windowWidth_t)){
      //   //高超出
      //   if(this.stage_height_original>windowHeight_t && this.stage_width_original<=windowWidth_t){
      //     heightDiff= this.stage_height_original-windowHeight_t;
      //     multiplying_power  = -heightDiff/this.stage_height_original;
      //     //this.stage_height_original = windowHeight_t;
      //   }
      //   //宽超出
      //   if(this.stage_width_original>windowWidth_t && this.stage_height_original<=windowHeight_t){
      //      widthDiff = this.stage_width_original-windowWidth_t;
      //      multiplying_power  = -widthDiff/this.stage_width_original;
      //      //this.stage_width_original = windowWidth_t;
      //   }
      // //两边同时超出，按高缩小
      // }else if(this.stage_height_original>windowHeight_t && this.stage_width_original>windowWidth_t){
      //   heightDiff= this.stage_height_original-windowHeight_t;
      //   multiplying_power  = -heightDiff/this.stage_height_original;
      //   //this.stage_height_original = windowHeight_t;
      // //两边同时小于视口，按高放大
      // }else if(this.stage_height_original<windowHeight_t && this.stage_width_original<windowWidth_t){
      //   heightDiff= windowHeight_t-this.stage_height_original;
      //   multiplying_power  = heightDiff/this.stage_height_original;

      // }else if(this.stage_height_original==windowHeight_t && this.stage_width_original==windowWidth_t){
      //   multiplying_power=0;
      // }else {
      heightDiff = windowHeight_t - this.stage_height_original;
      multiplying_power = heightDiff / this.stage_height_original;

      //}
      this.scaling = multiplying_power; //把比例存起来
      if (!this.isRotate) { // 宽屏
        //缩放
        var scaleFunc = "perspective(1px) scale(" + (multiplying_power + 1) + "," + (multiplying_power + 1) + ")";
        $('#container').css({
          "transform": scaleFunc, //缩放比例
          "-ms-transform": scaleFunc,
          "-moz-transform": scaleFunc,
          "-webkit-transform": scaleFunc,
          "-o-transform": scaleFunc,
        });
      } else { //手机 窄屏

        //正转 和 缩放
        var rotateFunc = "perspective(1px) rotateZ(" + rotateS + "deg) scale(" + (multiplying_power + 1) + "," + (
          multiplying_power + 1) + ")";
        var rotateBackgroundFunc = "rotateZ(" + rotateS + "deg)"; //背景
        $('#container').css({
          "transform": rotateFunc, //缩放比例
          "-ms-transform": rotateFunc,
          /* IE 9 */
          "-moz-transform": rotateFunc,
          /* Firefox */
          "-webkit-transform": rotateFunc,
          /* Safari 和 Chrome */
          "-o-transform": rotateFunc,
          /* Opera */
        });

        //背景设置
        $('#stageBackground').css({
          "transform": rotateBackgroundFunc, //缩放比例
          "transform-origin": "left top", //缩放基点
          "-ms-transform": rotateBackgroundFunc,
          /* IE 9 */
          "-ms-transform-origin": "left top",
          "-moz-transform": rotateBackgroundFunc,
          /* Firefox */
          "-moz-transform-origin": "left top",
          "-webkit-transform": rotateBackgroundFunc,
          /* Safari 和 Chrome */
          "-webkit-transform-origin": "left top",
          "-o-transform": rotateBackgroundFunc,
          /* Opera */
          "-o-transform-origin": "left top",
          "left": stageParent.width(),
          "height": stageParent.width(),
          "width": stageParent.height()
        });

        // 让画布div转回来 反转
        var rotateStage_Func = "rotateZ(-90deg)";
        $('#container .konvajs-content').css({
          "transform": rotateStage_Func, //缩放比例
          "transform-origin": "left top", //缩放基点

          "-ms-transform": rotateStage_Func,
          /* IE 9 */
          "-ms-transform-origin": "left top",

          "-moz-transform": rotateStage_Func,
          /* Firefox */
          "-moz-transform-origin": "left top",

          "-webkit-transform": rotateStage_Func,
          /* Safari 和 Chrome */
          "-webkit-transform-origin": "left top",

          "-o-transform": rotateStage_Func,
          /* Opera */
          "-o-transform-origin": "left top",

          "top": this.stage_height_original,

          height: this.stage_width_original,
          width: this.stage_height_original
        });

        $("#container").height(this.stage_height_original);
        $("#container").width(this.stage_width_original);

        // 设置 场景的宽度和高度 将场景的宽高对调
        this.stage.width(this.stage_height_original);
        this.stage.height(this.stage_width_original);
        // 然后旋转画布
        // this.stage.setAttr("offset",{x: this.stage_width_original,y: this.stage_height_original});
        this.stage.setAttr("offset", {
          x: 0,
          y: this.stage_height_original
        });
        this.stage.rotate(90);
        this.stage.draw();
      }

      this.stage.draw();


      $('#container').unbind('mousedown');
      $('#container').unbind('mousemove');
      $('#container').unbind('mouseup');
      $(document).unbind('mousemove');
      $(document).unbind('mouseup');
      //画面平移,监控时不使用平移
      // $(document).mousemove(function(e) {
      //     if (!!this.move) {
      //         var posix = !document.move_target ? {'x': 0, 'y': 0} : document.move_target.posix,
      //             callback = document.call_down || function() {
      //                 // var top_=(e.pageY - posix.y-2.5);
      //                 var top_=((e.pageY+(stageView.stage_height_original*(multiplying_power+1))/2)-(stageView.stage_height_original/2))-((windowHeight-canvasHeight)/2)-posix.y
      //                  var left_=((e.pageX+(stageView.stage_width_original*(multiplying_power+1))/2)-(stageView.stage_width_original/2))-((windowWidth-canvasWidth)/2)-posix.x;
      //                  //var left_=posix.x;
      //                      left_=left_;
      //                 $(this.move_target).css({
      //                     'top':top_,
      //                     'left':left_
      //                 });

      //             };
      //         callback.call(this, e, posix);
      //     }
      // }).mouseup(function(e) {
      //     if (!!this.move) {
      //         var callback = document.call_up || function(){};
      //         callback.call(this, e);
      //         $.extend(this, {
      //             'move': false,
      //             'move_target': null,
      //             'call_down': false,
      //             'call_up': false
      //         });
      //     }
      // });
      // $('#container').mousedown(function(e) {
      //     var offset = $(this).offset();
      //     this.posix = {'x': e.pageX - offset.left, 'y': e.pageY - offset.top};
      //     $.extend(document, {'move': true, 'move_target': this});
      // });


      if (this.stageMove) { //添加滚轮
        this.addMouseListens(this.stage);
      }

      if (this.isRotate) { //如果旋转说明是手机端，要去掉平移。去掉滚轮
        $('#container').unbind('mousedown');
        $('#container').unbind('mousemove');
        $('#container').unbind('mouseup');
        $(document).unbind('mousemove');
        $(document).unbind('mouseup');
        //取消滚轮
        var container = this.stage.container();
        container.removeEventListener('DOMMouseScroll', this.scrollFunc);
        container.onmousewheel = null;
      }
      var layerbackground = this.stage.getLayers()[0];
      if (this.stage.width() == 750) { //手机竖屏背景不铺满
        this.setStageBackground(layerbackground);
      } else {
        this.setDivBackground(); //设置div背景铺满
      }



      //this.setDivBackground();//设置div背景

    },
    /**
     * 如果是手机，不旋转，以宽为基准，计算高,用于手机端不旋转。该方法，本文件里面没有使用，使用的是上面的方法adaptPhoneWindows
     */
    adaptPhone: function() {
      //画面平移需要参数
      var iframeWindow = $("#container").parent(); //窗口大小
      var windowWidth = iframeWindow.width(); //窗口宽
      var windowHeight = iframeWindow.height(); //窗口高

      var canvasDiv = $("#container"); //画布
      var canvasWidth = canvasDiv.width(); //画布宽
      var canvasHeight = canvasDiv.height(); //画布高

      //还原上次对画布的所有设置 starat--------------------------------------------
      if (typeof(this.stage_height_original) != "undefined") {
        $("#container").height(""); //设置宽高=空，下面恢复stage原始状态的时候会自动设置
        $("#container").width("");
        // 恢复stage原始状态
        this.stage.width(this.stage_width_original);
        this.stage.height(this.stage_height_original);
        this.stage.scale({
          x: 1,
          y: 1
        });
        var stageRotation = this.stage.rotation();
        this.stage.rotate(-stageRotation);
        this.stage.setAttr("offset", {
          x: 0,
          y: 0
        });
        this.stage.draw();
        //拿到还原后的画布宽高
        canvasDiv = $("#container"); //画布
        canvasWidth = canvasDiv.width(); //画布宽
        canvasHeight = canvasDiv.height(); //画布高



        // 恢复s container 下 画布div 原始状态
        $('#container').css({
          'top': 0,
          'left': 0
        });
        var defaultRotateStage_Func = "rotateZ(0deg)";
        $('#container .konvajs-content').css({
          "transform": defaultRotateStage_Func, //缩放比例
          "transform-origin": "left top", //缩放基点

          "-ms-transform": defaultRotateStage_Func,
          "-ms-transform-origin": "left top",

          "-moz-transform": defaultRotateStage_Func,
          "-moz-transform-origin": "left top",

          "-webkit-transform": defaultRotateStage_Func,
          "-webkit-transform-origin": "left top",

          "-o-transform": defaultRotateStage_Func,
          "-o-transform-origin": "left top",

          "top": 0,

          // height:this.stage_height_original,//不要特意设置容器div的匡高，改属性有画布自动去决定
          //width:this.stage_width_original
        });

        // 恢复 container 原始状态
        var defaultRotateFunc = "rotateZ(0deg) scale(1,1)";
        $('#container').css({
          "transform": defaultRotateFunc, //缩放比例
          "-ms-transform": defaultRotateFunc,
          "-moz-transform": defaultRotateFunc,
          "-webkit-transform": defaultRotateFunc,
          "-o-transform": defaultRotateFunc,
        });

        //恢复背景设置
        var defaultStageBackground_Func = "rotateZ(0deg)";
        $('#stageBackground').css({
          "transform": defaultStageBackground_Func, //缩放比例
          "transform-origin": "left top", //缩放基点
          "-ms-transform": defaultStageBackground_Func,
          /* IE 9 */
          "-ms-transform-origin": "left top",
          "-moz-transform": defaultStageBackground_Func,
          /* Firefox */
          "-moz-transform-origin": "left top",
          "-webkit-transform": defaultStageBackground_Func,
          /* Safari 和 Chrome */
          "-webkit-transform-origin": "left top",
          "-o-transform": defaultStageBackground_Func,
          /* Opera */
          "-o-transform-origin": "left top",
          "left": 0,
          "height": '100%',
          "width": '100%'
        });
      }
      //还原上次对画布的所有设置 end----------------------------------------------------------------------------


      //保存场景的原始实际宽度和高度
      if (typeof(this.stage_height_original) == "undefined") {
        this.stage_height_original = canvasHeight;
        this.stage_width_original = canvasWidth;
      }

      var stageParent = $("#container").parent();
      var windowWidth_t = windowWidth;
      var windowHeight_t = windowHeight;
      var rotateS = 0;
      //计算放大百分比
      var widthtDiff = windowWidth_t - this.stage_width_original;
      var multiplying_power = widthtDiff / this.stage_width_original;
      this.scaling = multiplying_power; //把比例存起来
      //缩放
      var scaleFunc = "scale(" + (multiplying_power + 1) + "," + (multiplying_power + 1) + ")";
      $('#container').css({
        "transform": scaleFunc, //缩放比例
        "-ms-transform": scaleFunc,
        "-moz-transform": scaleFunc,
        "-webkit-transform": scaleFunc,
        "-o-transform": scaleFunc,
      });

      this.stage.draw();
      this.setDivBackground(); //设置div背景

    },
    /**
     * 去掉可移动属性
     */
    UnDrag: function() {
      var layerbackground = this.stage.getLayers()[0];
      if (this.stage.width() == 750) { //手机竖屏背景不铺满
        this.setStageBackground(layerbackground);
      }
      //this.setStageBackground(layerbackground);//不设置背景图片了，背景图片放在父级div这样可以铺满整个屏幕


      var groups = this.stage.find('Group');
      $(".yjzt_echart_class").remove(); //移除所有的echart元素div
      var stage_move = true;
      groups.each(function(group) {
        var moduleType = group.attrs.moduleType;
        var dataSourceType = group.attrs.dataSourceType || "liveData";
        console.log(dataSourceType);
        if (moduleType == 'HTML_IFRAME' || moduleType == 'DATA_IFRAME' || moduleType == 'MAP_IFRAME' ||
          moduleType == 'LIVE_IMAGES' || moduleType == 'MONITOR_IMAGES' || moduleType == 'SPBF_IMAGES' ||
          moduleType.indexOf("ECHART") != -1 || moduleType.indexOf("WEATHER") != -1) {
          stage_move = false;
        }
        group.draggable(false); //去掉可移动属性
        if (dataSourceType == "liveData") { //数据源为上报数据
          //设置文本组件的默认值
          stageView.setTextDefaultValue(group);
          stageView.setGroupImage(group);
          stageView.addClickEvent(group);
          //添加展示基础信息的事件  //鼠标点击弹框处理  在同一个方法里处理，否则鼠标放上去变手型事件会重复
          stageView.addBasicInfoEvent(group);
        } else { //数据源为平台数据
          //处理平台数据
          stageView.setPlatformData(group);
        }

      });
      this.layer.draw();
      return stage_move;
    },
    /**
     * 设置背景图层的图片
     */
    setStageBackground: function(backgroundLayer) {
      var stageWidth = this.stage.width();
      var stageHeight = this.stage.height();
      var urlImage = backgroundLayer.attrs.backgroundImageURL;
      if (typeof(urlImage) != "undefined" && urlImage != "") {
        //删除原有的 image 组件。
        var nodes = backgroundLayer.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        Konva.Image.fromURL(urlImage, function(imageNode) {
          imageNode.name("myShapeBackgroundImage");
          imageNode.width(stageWidth);
          imageNode.height(stageHeight);
          backgroundLayer.add(imageNode);
          //moduleObject.draw();
          backgroundLayer.draw();
        }, "config/gyyj/noimg.svg");

      }


    },
    //设置文本组件的默认值
    setTextDefaultValue: function(moduleObject) {
      var moduleType = moduleObject.attrs.moduleType;
      if (moduleType == 'TextLableValue') {
        var defauleValue = moduleObject.attrs.defaultValue;
        var unit = moduleObject.attrs.unit || '';
        var moudleShapeDes = moduleObject.find('.description')[0];
        //描述外面的框
        var descriptionobjRect = moduleObject.find('.descriptionRect')[0];
        descriptionobjRect.width(moudleShapeDes.getWidth());
        descriptionobjRect.height(moudleShapeDes.getHeight());

        //值 xy设置
        var complexTextValue = moduleObject.find('.complexTextValue')[0];
        complexTextValue.setAttr("text", defauleValue + unit);
        complexTextValue.x(moudleShapeDes.x() + moudleShapeDes.getWidth());
        complexTextValue.y(moudleShapeDes.y());
        //值的框 xy设置
        var rectValue = moduleObject.find('.rectValue')[0];
        rectValue.x(moudleShapeDes.x() + moudleShapeDes.getWidth());
        rectValue.y(moudleShapeDes.y());
        rectValue.width(complexTextValue.getWidth());
        rectValue.height(complexTextValue.getHeight());

      }
      if (moduleType == 'VALUE') {
        var defauleValue = moduleObject.attrs.defaultValue;
        var unit = moduleObject.attrs.unit || '';
        //值 xy设置
        var complexTextValue = moduleObject.find('.complexTextValue')[0];
        complexTextValue.setAttr("text", defauleValue + unit);


      }
      if (moduleType == 'STATUSVALUE') {
        var defauleValue = moduleObject.attrs.defaultValue;
        //值 xy设置
        var complexTextValue = moduleObject.find('.complexTextValue')[0];
        complexTextValue.setAttr("text", defauleValue);
      }
      if (moduleType == 'CURRENTDATE') { //当前时间
        var dateFormat = moduleObject.attrs.dateFormat;
        var complexTextValue = moduleObject.find('.complexTextValue')[0];


        setInterval(function() {
          complexTextValue.setAttr("text", new Date().dateFormat(dateFormat));
          moduleObject.getLayer().draw();
        }, 1000);


      }




    },

    //封装一个请求函数
    requestData(data, url) {
      var resData = null;
      $.ajax({
        type: "POST",
        url: baseURL + url,
        data: data,
        cache: false,
        async: false, //这里用同步
        beforeSend: function() {
          //请求前要处理的事情
        },
        success: function(data) { //保存成功后，返回data，里面包含 stage_id  ,应为再次点击“保存”就是修改
          if (data && data.result == 'success') {
            resData = data.data;
          } else {
            layer.msg(data.msg, {
              offset: 't',
              anim: 6,
              icon: 2
            });
            return null;
          }

        },
        error: function(jqXHR) {
          console.log("发生错误：" + jqXHR.status);
          return null;
        }
      });
      return resData;

    },
    //不同接口对应不同参数判断
    getApiArg(api, equipId = "", sensorCode, method, dateType, totalArea) {
      var arg = {};
      switch (api) {
        case "/api/index/counts": //总计
          arg = {
            "product_id": totalArea == "thisOption" ? localStorage.getItem("optionId") : '',
            "token": localStorage.getItem("attoken")
          };
          break;
        case "/api/alarm/counts": //报警统计
        case "/api/equip/counts": //设备统计
          arg = {
            "product_id": totalArea == "thisOption" ? localStorage.getItem("optionId") : '',
            "token": localStorage.getItem("attoken")
          };
          break;
        case "/api/equip/info": //设备信息
          arg = {
            "product_id": localStorage.getItem("optionId"),
            "id": equipId,
            "token": localStorage.getItem("attoken")
          };
          break;
        case "/api/sensor/analysis": //设备信息
          arg = {
            "sensor_code": sensorCode,
            "function": method,
            "date_type": dateType,
            "token": localStorage.getItem("attoken")
          };
          break;

      }
      return arg;

    },

    //处理数据源属性为platform的组件
    setPlatformModule: function(moduleObject, moduleType, field, dataArg, api, dataKeyArray) {
      var resData = stageView.requestData(dataArg, api); //通过对应接口获取数据
      if (!resData) {
        return;
      }
      //console.log(resData);
      if (moduleType == 'TextLableValue') { //变量1

        var defauleValue = moduleObject.attrs.defaultValue;
        var nowValue = '';
        if (api == "/api/sensor/analysis") { //单点数据分析时，返回的数组，取数组的第一个对象的value；
          nowValue = resData[0].value;
        } else {
          nowValue = resData[field];
        }
        console.log(nowValue);
        var unit = moduleObject.attrs.unit || '';
        var moudleShapeDes = moduleObject.find('.description')[0];
        //描述外面的框
        var descriptionobjRect = moduleObject.find('.descriptionRect')[0];
        descriptionobjRect.width(moudleShapeDes.getWidth());
        descriptionobjRect.height(moudleShapeDes.getHeight());

        //值 xy设置
        var complexTextValue = moduleObject.find('.complexTextValue')[0];
        complexTextValue.setAttr("text", nowValue + unit);
        complexTextValue.x(moudleShapeDes.x() + moudleShapeDes.getWidth());
        complexTextValue.y(moudleShapeDes.y());
        //值的框 xy设置
        var rectValue = moduleObject.find('.rectValue')[0];
        rectValue.x(moudleShapeDes.x() + moudleShapeDes.getWidth());
        rectValue.y(moudleShapeDes.y());
        rectValue.width(complexTextValue.getWidth());
        rectValue.height(complexTextValue.getHeight());

      }
      if (moduleType == 'VALUE') { //变量2
        var defauleValue = moduleObject.attrs.defaultValue;
        var nowValue = '';
        if (api == "/api/sensor/analysis") { //单点数据分析时，返回的数组，取数组的第一个对象的value；
          nowValue = resData[0].value;
        } else {
          nowValue = resData[field];
        }
        var unit = moduleObject.attrs.unit || '';
        //值 xy设置
        var complexTextValue = moduleObject.find('.complexTextValue')[0];
        complexTextValue.setAttr("text", nowValue + unit);


      }
      if (moduleType.indexOf("STATUS") >= 0) {
        var defauleValue = moduleObject.attrs.defaultValue || 0;
        var nowValue = '';
        if (api == "/api/sensor/analysis") { //单点数据分析时，返回的数组，取数组的第一个对象的value；
          nowValue = resData[0].value || '';
        } else {
          nowValue = resData[field] || defauleValue;
        }
        //stageData的格式
        //{"D0010@232_Slave1@1":99}
        //为了格式一致做的组合
        var fieldStr = field + "@" + field + "@" + field;
        //对象键为变量时，要加[]
        var stageData = {
          [fieldStr]: nowValue
        };
        //console.log(stageData);
        //this.setInfoData(stageData);// 设置组件基础数据

        var hideMethodCall = moduleObject.attrs.hideMethodCall; //隐藏要调用的方法
        var sparklingMethodCall = moduleObject.attrs.sparklingMethodCall; //闪烁要调用的方法
        if (typeof(hideMethodCall) != "undefined" && hideMethodCall !== "") { //隐藏
          //console.log("2="+groupTemp);
          moduleAnimation.hideModule(moduleObject, stageData);
        }

        if (typeof(sparklingMethodCall) != "undefined" && sparklingMethodCall !== "") { //闪烁
          //console.log("3="+groupTemp);
          moduleAnimation.sparklingModule(moduleObject, stageData);

        }
        if (moduleType == 'STATUSVALUE') { //状态文字
          moduleAnimation.setStatusValue(moduleObject, stageData);
        }
        if (moduleType == 'STATUSLIGHT') { //状态灯
          moduleAnimation.setStatusLight(moduleObject, stageData);
        }
        if (moduleType == "IMAGES_STATUS") { //状态图片
          moduleAnimation.setImageStatusValue(moduleObject, stageData, fieldStr);
        }
      }
      //处理平台数据echart组件
      if (moduleType.indexOf("ECHART") != -1 && typeof(moduleType) != "undefined") {
        for (var n = 0, len2 = dataKeyArray.length; n < len2; n++) {
          for (var m = 0, len3 = resData.length; m < len3; m++) {
            if (dataKeyArray[n].key == resData[m].sensor_code) {
              dataKeyArray[n].value = resData[m].value;
            }
          }
        }

        var divid = Math.uuid();
        moduleObject.id(divid); //给组件设置id方便动画的时候好找

        var urlImage = moduleObject.attrs.echartURL;
        var divWidth = moduleObject.attrs.width * moduleObject.scale().x;
        var divHeight = moduleObject.attrs.height * moduleObject.scale().y;
        //删除原有的 image 组件。
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        var stageBox = this.stage.container().getBoundingClientRect();
        // so position of textarea will be the sum of positions above:
        var areaPosition = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };
        var divnode = document.createElement('div');
        divnode.id = divid;
        document.getElementById("container").appendChild(divnode);
        //document.body.appendChild(divnode);
        divnode.className = 'yjzt_echart_class';
        divnode.style.height = divHeight + 'px';
        divnode.style.width = divWidth + 'px';
        divnode.style.position = 'absolute';
        divnode.style.top = areaPosition.y + 'px';
        divnode.style.left = areaPosition.x + 'px';
        var myChart = echarts.init(divnode);
        if (moduleType == "ECHART_realTimeBarGraph") { //实时柱状图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var sortType = moduleObject.attrs.sortType || '0';
          console.log(sortType);
          if (sortType == '1') {
            echartOption.series[0].realtimeSort = true;
            echartOption.xAxis.inverse = true;
          } else if (sortType == '2') {
            echartOption.series[0].realtimeSort = true;
            echartOption.xAxis.inverse = false;
          } else if (sortType == '0') {
            echartOption.series[0].realtimeSort = false;
          }
          var unit = moduleObject.attrs.unit; //X零轴线颜色
          var BarGraphLableColor = moduleObject.attrs.BarGraphLableColor; //柱子文字颜色
          var zeroAxisColorX = moduleObject.attrs.zeroAxisColorX; //X零轴线颜色
          var lableColorX = moduleObject.attrs.lableColorX; //XY轴文字颜色
          //var  lableColorY=moduleObject.attrs.lableColorY;//Y轴文字颜色
          var horizontalSplitColor = moduleObject.attrs.horizontalSplitColor; //横向分割线颜色

          var xAxis_data = new Array();
          var series_dataarray = new Array();
          echartOption.xAxis.axisLabel.rotate = dataKeyArray.length <= 6 ? 0 : 30;
          echartOption.xAxis.max = dataKeyArray.length - 1;
          for (var i = 0; i < dataKeyArray.length; i++) {
            xAxis_data.push(dataKeyArray[i].name);
            series_dataarray.push(dataKeyArray[i].value);
          }
          echartOption.xAxis.data = xAxis_data;
          echartOption.xAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.yAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.xAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.splitLine.lineStyle.color = horizontalSplitColor;
          echartOption.series[0].data = series_dataarray;
          echartOption.series[0].label.formatter = function(params) {
            return params.value + unit;
          };
          echartOption.series[0].label.color = BarGraphLableColor;
          myChart.setOption(echartOption);


        }

        if (moduleType == "ECHART_realTimeSortBar") { //实时横条排序
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var sortType = moduleObject.attrs.sortType || '1';
          var AxisShowTypeX = moduleObject.attrs.AxisShowTypeX || "hidden";
          console.log(sortType);
          if (sortType == '1') {
            echartOption.series[0].realtimeSort = true;
            echartOption.yAxis.inverse = true;
          } else if (sortType == '2') {
            echartOption.series[0].realtimeSort = true;
            echartOption.yAxis.inverse = false;
          } else if (sortType == '0') {
            echartOption.series[0].realtimeSort = false;
          }
          console.log(AxisShowTypeX);
          if (AxisShowTypeX == 'hidden') { //不显示X轴和刻度标记
            echartOption.xAxis.axisLine.show = false;
            echartOption.xAxis.axisTick.show = false;
          } else if (AxisShowTypeX == 'normal') { //正常显示X轴和刻度标记
            echartOption.xAxis.axisLine.show = true;
            echartOption.xAxis.axisTick.show = true;
          } else if (AxisShowTypeX == 'point') { //只显示X轴刻度标记
            echartOption.xAxis.axisLine.show = false;
            echartOption.xAxis.axisTick.show = true;
          }
          var unit = moduleObject.attrs.unit; //X零轴线颜色
          var BarGraphNumberColor = moduleObject.attrs.BarGraphNumberColor; //柱子文字颜色
          var verticalSplitColor = moduleObject.attrs.verticalSplitColor || "transparent"; //竖向分割线颜色
          var zeroAxisColorX = moduleObject.attrs.zeroAxisColorX; //X零轴线颜色
          var lableColorX = moduleObject.attrs.lableColorX; //X轴文字颜色
          // var  lableColorY=moduleObject.attrs.lableColorY;//Y轴文字颜色
          //var  horizontalSplitColor=moduleObject.attrs.horizontalSplitColor;//横向分割线颜色

          var yAxis_data = new Array();
          var series_dataarray = new Array();
          //console.log(dataKeyArray.length);
          echartOption.yAxis.max = dataKeyArray.length - 1;
          for (var g = 0; g < dataKeyArray.length; g++) {
            yAxis_data.push(dataKeyArray[g].name);
            series_dataarray.push(dataKeyArray[g].value);
          }
          echartOption.yAxis.data = yAxis_data;
          echartOption.xAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.yAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.xAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.xAxis.splitLine.lineStyle.color = verticalSplitColor;
          echartOption.series[0].data = series_dataarray;
          echartOption.series[0].label.formatter = function(params) {
            return params.value + unit;
          };
          echartOption.series[0].label.color = BarGraphNumberColor;
          myChart.setOption(echartOption);
        }

        if (moduleType == "ECHART_realTimePieGraph") { //实时饼图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");


          var legendColor = moduleObject.attrs.legendColor; //图例文字颜色
          var lableColor = moduleObject.attrs.lableColor; //饼内数字颜色

          var series_dataarray = new Array();
          for (var p = 0; p < dataKeyArray.length; p++) {
            series_dataarray.push({
              value: dataKeyArray[p].value,
              name: dataKeyArray[p].name
            });
          }

          echartOption.legend.textStyle.color = legendColor;
          echartOption.series[0].label.color = lableColor;
          echartOption.series[0].data = series_dataarray;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_realTimeCircularGraph") { //实时环形图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");


          var legendColor = moduleObject.attrs.legendColor; //图例文字颜色
          var lableColor = moduleObject.attrs.lableColor; //饼内数字颜色

          var series_dataarray = new Array();
          for (var i = 0; i < dataKeyArray.length; i++) {
            series_dataarray.push({
              value: dataKeyArray[i].value,
              name: dataKeyArray[i].name
            });
          }

          echartOption.legend.textStyle.color = legendColor;
          echartOption.series[0].label.color = lableColor;
          echartOption.series[0].data = series_dataarray;
          myChart.setOption(echartOption);
        }



      }
    },


    //设置平台数据源数据2023年2月18日新增
    setPlatformData: function(moduleObject) {
      var that = this;
      console.log(moduleObject.attrs);
      var moduleType = moduleObject.attrs.moduleType;
      var refreshInterval = Number(moduleObject.attrs.refreshType) || 0;
      console.log(refreshInterval);
      //获取统计范围
      var totalArea = moduleObject.attrs.totalArea;
      var dataKeyArray = [];
      try {
        dataKeyArray = eval(moduleObject.attrs.dataKey);
      } catch (e) {
        dataKeyArray = eval("[" + moduleObject.attrs.dataKey + "]"); //兼容之前创建好的画面
      }
      var api = moduleObject.attrs.dataAPIType;
      var field = moduleObject.attrs.field;
      var equipId = moduleObject.attrs.equipId || ''; //只在设备信息会用到设备id
      //以下三个暂时只有单点数据分析用到，2023月3月1日
      var sensorCode = '';
      if (api == "/api/sensor/analysis" && moduleType.indexOf("ECHART") < 0) {
        sensorCode = dataKeyArray[0].key ? dataKeyArray[0].key : '';
      } else if (api == "/api/sensor/analysis" && moduleType.indexOf("ECHART") >= 0) {
        var sensorCodeArray = [];
        for (var k = 0, len = dataKeyArray.length; k < len; k++) {
          sensorCodeArray.push(dataKeyArray[k].key);
        }
        sensorCode = sensorCodeArray.join(',');
        //console.log(sensorCode);
      }

      var method = api == "/api/sensor/analysis" ? moduleObject.attrs['function'] : '';
      var dateType = api == "/api/sensor/analysis" ? moduleObject.attrs.dateType : '';

      var dataArg = stageView.getApiArg(api, equipId, sensorCode, method, dateType, totalArea); //获取接口对应所需的参数对象
      if (refreshInterval <= 0) {
        this.setPlatformModule(moduleObject, moduleType, field, dataArg, api, dataKeyArray);
      } else {
        this.setPlatformModule(moduleObject, moduleType, field, dataArg, api, dataKeyArray);
        setInterval(function() {
          that.setPlatformModule(moduleObject, moduleType, field, dataArg, api, dataKeyArray);
        }, refreshInterval * 1000);
      }
    },


    /**
     * 如果是图片或svg要重新初始化
     */
    setGroupImage: function(moduleObject) {

      var moduleType = moduleObject.attrs.moduleType;
      //2024年7月31日从正式平台复制按钮背景的初始化
      if ((moduleType == "BUTTON" || moduleType == "BUTTONVALUE") && moduleObject.attrs.btnImageUrl) {
        var moudleShapeDes = moduleObject.get('.buttonText')[0];
        //描述外面的框
        var descriptionobjRect = moduleObject.get('.buttonRect')[0];
        descriptionobjRect.width(moudleShapeDes.getWidth());
        descriptionobjRect.height(moudleShapeDes.getHeight());
        var imageObj = new Image();
        imageObj.crossOrigin = 'Anonymous';
        imageObj.src = moduleObject.attrs.btnImageUrl;
        imageObj.onload = function() {
          descriptionobjRect.fillPatternRepeat('no-repeat');
          descriptionobjRect.fillPatternOffset({
            x: 0,
            y: 0
          });
          var w = descriptionobjRect.getWidth() / imageObj.width;
          var h = descriptionobjRect.getHeight() / imageObj.height;
          descriptionobjRect.fillPatternImage(imageObj);
          descriptionobjRect.fillPatternScale({
            x: w,
            y: h
          });
          descriptionobjRect.getLayer().draw();
        }
      }
      if ((moduleType.indexOf("IMAGES") != -1 || moduleType.indexOf("SVG") != -1) && typeof(moduleType) !=
        "undefined" && moduleType.indexOf("LIVE_IMAGES") == -1 && moduleType.indexOf("MONITOR_IMAGES") == -1 &&
        moduleType.indexOf("SPBF_IMAGES") == -1 && moduleType.indexOf("WEATHER_IMAGES") == -1) {
        var urlImage = moduleObject.attrs.imageURL;
        //删除原有的 image 组件。
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });


        if (urlImage.indexOf(".gif") == -1) {
          Konva.Image.fromURL(urlImage, function(imageNode) {
            imageNode.name("myShape");
            if (moduleType != "LIVE_IMAGES") {
              imageNode.setAttr("offset", {
                x: imageNode.width() / 2,
                y: imageNode.height() / 2,
              });
            }
            moduleObject.add(imageNode);
            //moduleObject.draw();
            stageView.layer.draw();
          }, "config/gyyj/noimg.svg");
        } else {
          var canvas = document.createElement('canvas');
          var image;
          var statusIn_add = false;
          gifler(urlImage).frames(canvas, function(ctx, frame) {
            // update canvas size
            canvas.width = frame.width;
            canvas.height = frame.height;
            // update canvas that we are using for Konva.Image
            ctx.drawImage(frame.buffer, 0, 0);
            // redraw the layer
            stageView.layer.batchDraw();
            if (!statusIn_add) {
              image = new Konva.Image({
                image: canvas,
                offset: {
                  x: canvas.width / 2,
                  y: canvas.height / 2
                }
              });
              moduleObject.add(image);
              statusIn_add = true;
            }



          });
        }



      }

      if ((moduleType.indexOf("GIF") != -1) && typeof(moduleType) != "undefined") { // gif动画处理
        var urlImage = moduleObject.attrs.imageURL;
        //删除原有的 image 组件。
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });

        var canvas = document.createElement('canvas');
        gifler(urlImage).frames(canvas, function(ctx, frame) {
          // update canvas size
          canvas.width = frame.width;
          canvas.height = frame.height;
          // update canvas that we are using for Konva.Image
          ctx.drawImage(frame.buffer, 0, 0);
          // redraw the layer
          stageView.layer.batchDraw();
        });
        var image = new Konva.Image({
          image: canvas,
        });

        moduleObject.add(image);



      }



      //如果是echart组件
      if (moduleType.indexOf("ECHART") != -1 && typeof(moduleType) != "undefined") {
        var divid = Math.uuid();
        moduleObject.id(divid); //给组件设置id方便动画的时候好找

        var urlImage = moduleObject.attrs.echartURL;
        var divWidth = moduleObject.attrs.width * moduleObject.scale().x;
        var divHeight = moduleObject.attrs.height * moduleObject.scale().y;
        //删除原有的 image 组件。
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        var stageBox = this.stage.container().getBoundingClientRect();
        // so position of textarea will be the sum of positions above:
        var areaPosition = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };
        var divnode = document.createElement('div');
        divnode.id = divid;
        document.getElementById("container").appendChild(divnode);
        //document.body.appendChild(divnode);
        divnode.className = 'yjzt_echart_class';
        divnode.style.height = divHeight + 'px';
        divnode.style.width = divWidth + 'px';
        divnode.style.position = 'absolute';
        divnode.style.top = areaPosition.y + 'px';
        divnode.style.left = areaPosition.x + 'px';
        // divnode.style.top =  0 + 'px';
        //divnode.style.left = 0 + 'px';
        // var myChart = echarts.init(document.getElementById('main'));
        var myChart = echarts.init(divnode);

        if (moduleType == "ECHART_GAUGE") { //仪表盘
          var echart_option = eval(moduleObject.attrs.echartURL + "()");
          for (var i = 0; i < echart_option.series.length; i++) {
            echart_option.series[i].max = Number(moduleObject.attrs.maxValue);
            echart_option.series[i].min = Number(moduleObject.attrs.minValue);
          }
          myChart.setOption(echart_option);
        }
        if (moduleType == "ECHART_THERMOMETER") { //温度计
          var maxValue = moduleObject.attrs.maxValue;
          var minValue = moduleObject.attrs.minValue;
          myChart.setOption(eval(moduleObject.attrs.echartURL + "(0," + maxValue + "," + minValue + ")"));
        }
        if (moduleType == "ECHART_realTimeLine") { //实时折线图
          myChart.setOption(eval(moduleObject.attrs.echartURL + "(0)"));
        }
        if (moduleType == "ECHART_realTimeLineNew") { //实时则线图新
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);

          var titleColor = moduleObject.attrs.titleColor; //头部分类颜色
          var zeroAxisColorX = moduleObject.attrs.zeroAxisColorX; //X零轴线颜色
          var lableColorX = moduleObject.attrs.lableColorX; //X轴文字颜色
          //暂时不要横竖分割线
          //var  verticalSplitColor=moduleObject.attrs.verticalSplitColor;//竖向分割线颜色
          var lableColorY = moduleObject.attrs.lableColorY; //Y轴文字颜色
          //var  horizontalSplitColor=moduleObject.attrs.horizontalSplitColor;//横向分割线颜色
          var legend_data = new Array();
          var series_array = new Array();
          for (var i = 0; i < dataKeyArray.length; i++) {
            legend_data.push(dataKeyArray[i].name);
            series_array.push({
              name: dataKeyArray[i].name,
              type: 'line',
              data: [],
              smooth: true

            })
          }
          echartOption.legend.data = legend_data;
          echartOption.legend.textStyle.color = titleColor;
          //2022年5月5日改为Y轴和X轴颜色一样
          echartOption.xAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.yAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.xAxis.axisLabel.textStyle.color = lableColorX;
          //暂时不要横竖分割线
          //echartOption.xAxis.splitLine.lineStyle.color=verticalSplitColor;
          echartOption.yAxis.axisLabel.textStyle.color = lableColorY;
          //echartOption.yAxis.splitLine.lineStyle.color=horizontalSplitColor;
          //echartOption.xAxis.data=['00:00'];
          echartOption.xAxis.data = [];
          echartOption.series = series_array;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_realTimeBarGraph") { //实时柱状图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);
          console.log(dataKeyArray);
          var sortType = moduleObject.attrs.sortType || '0';
          console.log(sortType);
          if (sortType == '1') {
            echartOption.series[0].realtimeSort = true;
            echartOption.xAxis.inverse = true;
          } else if (sortType == '2') {
            echartOption.series[0].realtimeSort = true;
            echartOption.xAxis.inverse = false;
          } else if (sortType == '0') {
            echartOption.series[0].realtimeSort = false;
          }
          var unit = moduleObject.attrs.unit; //X零轴线颜色
          var BarGraphLableColor = moduleObject.attrs.BarGraphLableColor; //柱子文字颜色
          var zeroAxisColorX = moduleObject.attrs.zeroAxisColorX; //X零轴线颜色
          var lableColorX = moduleObject.attrs.lableColorX; //X轴文字颜色
          var lableColorY = moduleObject.attrs.lableColorY; //Y轴文字颜色
          var horizontalSplitColor = moduleObject.attrs.horizontalSplitColor; //横向分割线颜色

          var xAxis_data = new Array();
          var series_dataarray = new Array();
          echartOption.xAxis.axisLabel.rotate = dataKeyArray.length <= 6 ? 0 : 30;
          echartOption.xAxis.max = dataKeyArray.length - 1;
          for (var i = 0; i < dataKeyArray.length; i++) {
            xAxis_data.push(dataKeyArray[i].name);
            series_dataarray.push(0);
          }
          echartOption.xAxis.data = xAxis_data;
          echartOption.xAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.yAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.xAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.splitLine.lineStyle.color = horizontalSplitColor;
          echartOption.series[0].data = series_dataarray;
          echartOption.series[0].label.formatter = function(params) {
            return params.value + unit;
          };
          echartOption.series[0].label.color = BarGraphLableColor;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_realTimeSortBar") { //实时横条排序
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);
          var sortType = moduleObject.attrs.sortType || '1';
          var AxisShowTypeX = moduleObject.attrs.AxisShowTypeX || "hidden";
          console.log(sortType);
          if (sortType == '1') {
            echartOption.series[0].realtimeSort = true;
            echartOption.yAxis.inverse = true;
          } else if (sortType == '2') {
            echartOption.series[0].realtimeSort = true;
            echartOption.yAxis.inverse = false;
          } else if (sortType == '0') {
            echartOption.series[0].realtimeSort = false;
          }
          console.log(AxisShowTypeX);
          if (AxisShowTypeX == 'hidden') { //不显示X轴和刻度标记
            echartOption.xAxis.axisLine.show = false;
            echartOption.xAxis.axisTick.show = false;
          } else if (AxisShowTypeX == 'normal') { //正常显示X轴和刻度标记
            echartOption.xAxis.axisLine.show = true;
            echartOption.xAxis.axisTick.show = true;
          } else if (AxisShowTypeX == 'point') { //只显示X轴刻度标记
            echartOption.xAxis.axisLine.show = false;
            echartOption.xAxis.axisTick.show = true;
          }
          var unit = moduleObject.attrs.unit; //X零轴线颜色
          var BarGraphNumberColor = moduleObject.attrs.BarGraphNumberColor; //柱子文字颜色
          var verticalSplitColor = moduleObject.attrs.verticalSplitColor || "transparent"; //竖向分割线颜色
          var zeroAxisColorX = moduleObject.attrs.zeroAxisColorX; //X零轴线颜色
          var lableColorX = moduleObject.attrs.lableColorX; //X轴文字颜色
          // var  lableColorY=moduleObject.attrs.lableColorY;//Y轴文字颜色
          //var  horizontalSplitColor=moduleObject.attrs.horizontalSplitColor;//横向分割线颜色

          var yAxis_data = new Array();
          var series_dataarray = new Array();
          //console.log(dataKeyArray.length);
          echartOption.yAxis.max = dataKeyArray.length - 1;
          for (var i = 0; i < dataKeyArray.length; i++) {
            yAxis_data.push(dataKeyArray[i].name);
            series_dataarray.push(0);
          }
          echartOption.yAxis.data = yAxis_data;
          echartOption.xAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.yAxis.axisLine.lineStyle.color = zeroAxisColorX;
          echartOption.xAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.yAxis.axisLabel.textStyle.color = lableColorX;
          echartOption.xAxis.splitLine.lineStyle.color = verticalSplitColor;
          echartOption.series[0].data = series_dataarray;
          echartOption.series[0].label.formatter = function(params) {
            return params.value + unit;
          };
          echartOption.series[0].label.color = BarGraphNumberColor;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_realTimePieGraph") { //实时饼图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);

          var legendColor = moduleObject.attrs.legendColor; //图例文字颜色
          var lableColor = moduleObject.attrs.lableColor; //饼内数字颜色

          var series_dataarray = new Array();
          for (var i = 0; i < dataKeyArray.length; i++) {
            series_dataarray.push({
              value: 0,
              name: dataKeyArray[i].name
            });
          }

          echartOption.legend.textStyle.color = legendColor;
          echartOption.series[0].label.color = lableColor;
          echartOption.series[0].data = series_dataarray;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_realTimeCircularGraph") { //实时环形图
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);

          var legendColor = moduleObject.attrs.legendColor; //图例文字颜色
          var lableColor = moduleObject.attrs.lableColor; //饼内数字颜色

          var series_dataarray = new Array();
          for (var i = 0; i < dataKeyArray.length; i++) {
            series_dataarray.push({
              value: 0,
              name: dataKeyArray[i].name
            });
          }

          echartOption.legend.textStyle.color = legendColor;
          echartOption.series[0].label.color = lableColor;
          echartOption.series[0].data = series_dataarray;
          myChart.setOption(echartOption);
        }
        if (moduleType == "ECHART_Pool") { //
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);

          var waterColor = moduleObject.attrs.waterColor //水的颜色
          var backgroundColor = moduleObject.attrs.backgroundColor //背景颜色
          var borderWidth = moduleObject.attrs.borderWidth //边框宽度
          var borderColor = moduleObject.attrs.borderColor //边框颜色

          echartOption.series[0].color[0] = waterColor;
          echartOption.series[0].backgroundStyle.borderWidth = borderWidth;
          echartOption.series[0].backgroundStyle.borderColor = borderColor;
          echartOption.series[0].backgroundStyle.color = backgroundColor;

          myChart.setOption(echartOption);
          // myChart.setOption(eval(moduleObject.attrs.echartURL+"(0)"));
        }

        if (moduleType == "ECHART_Pool2") { //
          var echartOption = eval(moduleObject.attrs.echartURL + "()");
          var dataKeyArray = eval(moduleObject.attrs.dataKey);

          var waterColor = moduleObject.attrs.waterColor //水的颜色
          var backgroundColor = moduleObject.attrs.backgroundColor //背景颜色

          echartOption.series[1].itemStyle.normal.color = waterColor;
          echartOption.series[2].itemStyle.normal.color = waterColor;
          echartOption.series[4].itemStyle.normal.color = waterColor;
          echartOption.series[0].itemStyle.color = backgroundColor;
          echartOption.series[3].itemStyle.color = backgroundColor;

          myChart.setOption(echartOption);
        }
      }
      //如果是iframe组件
      if (moduleType.indexOf("IFRAME") != -1 && typeof(moduleType) != "undefined") {

        //新加历史曲线组件获取code数组；
        var sensorCodes = [];
        //获取颜色函数，地址参数中不能出现"#"号，所以颜色值要去掉“#”
        function getColor(color, defaultColor = "111111") {
          if (!color) { //没设颜色则取默认值
            return '*' + defaultColor;
          } else if (color.indexOf("#") == 0) { //十六进制色值去“#”号,换为“*”
            return '*' + color.substr(1, color.length - 1);
          } else { //其他颜色值写法
            return color
          }
        };

        var iframeSrc = moduleObject.attrs.iframeSrc;
        //console.log(iframeSrc);
        if (moduleType == "HTML_IFRAME") {
          var insertType = moduleObject.attrs.insertType || "web";
          if (insertType == "view") {
            console.log(moduleObject.attrs.insertView);
            iframeSrc = "client_view.html?stageId=" + moduleObject.attrs.insertView;
          }
        }

        var box = moduleObject.getClientRect();
        var iframeWidth = box.width;
        var iframeHeight = box.height;
        //删除边框和文字
        var nodes1 = moduleObject.find('Text');
        nodes1.each(function(node) {
          node.destroy();
        });
        var nodes2 = moduleObject.find('Rect');
        nodes2.each(function(node) {
          node.destroy();
        });
        this.layer.draw();
        var stageBox = this.stage.container().getBoundingClientRect();
        // so position of textarea will be the sum of positions above:
        var areaPosition = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };

        var iframeNode = document.createElement('iframe');
        document.getElementById("container").appendChild(iframeNode);
        //document.body.appendChild(iframeNode);
        iframeNode.className = 'yjzt_echart_class';
        iframeNode.style.height = iframeHeight + 'px';
        iframeNode.style.width = iframeWidth + 'px';
        iframeNode.style.position = 'absolute';
        iframeNode.style.top = areaPosition.y + 'px';
        iframeNode.style.left = areaPosition.x + 'px';
        iframeNode.src = iframeSrc;
        if (moduleType == "DATA_IFRAME") {
         // console.log(moduleObject.attrs);
          var tableStyle = {
            "searchColor":moduleObject.attrs.searchColor,
            "headBackground": moduleObject.attrs.headBackground,
            "fieldColor": moduleObject.attrs.fieldColor,
            "tableBorderColor": moduleObject.attrs.tableBorderColor,
            "tableTextColor": moduleObject.attrs.tableTextColor
          };

          //    var headBackground=moduleObject.attrs.headBackground;
          //    var fieldColor=moduleObject.attrs.fieldColor;
          //    var tableBorderColor=moduleObject.attrs.tableBorderColor;
          // var tableTextColor = moduleObject.attrs.tableTextColor;

          if (!tableStyle.searchColor && !tableStyle.headBackground && !tableStyle.fieldColor && !tableStyle.tableBorderColor && !tableStyle
            .tableTextColor) {
            tableStyle = "";
          } else {
            localStorage.setItem("tableStyle", JSON.stringify(tableStyle));
          }
          var boxBackground = getColor(moduleObject.attrs.boxBackground,'');
          var sensorBoxColor = getColor(moduleObject.attrs.sensorBoxColor,'*00d8d8');
          // console.log(JSON.stringify(tableStyle));
          var borderWidth = moduleObject.attrs.borderWidth;
          //边框颜色
          var borderColor = getColor(moduleObject.attrs.borderColor, 'transparent');
          var borderRadius = moduleObject.attrs.borderRadius;
          var pageSize = moduleObject.attrs.pageSize || 10;
         // console.log(pageSize);
          var defaultArgments = moduleObject.attrs.defaultArgments || "";
          //iframeNode.src = iframeSrc+"?default="+defaultArgments+"&type="+moduleObject.attrs.tabTypes+"&showStyle="+moduleObject.attrs.showStyle+"&headBackground="+headBackground+"&fieldColor="+fieldColor+"&tableBorderColor="+tableBorderColor+"&tableTextColor="+tableTextColor+"&borderWidth="+borderWidth+"&borderColor="+borderColor+"&borderRadius="+borderRadius;
          iframeNode.src = iframeSrc + "?default=" + defaultArgments + "&type=" + moduleObject.attrs.tabTypes +
            "&showType=" + moduleObject.attrs.showType+"&boxBackground="+boxBackground+"&sensorBoxColor="+sensorBoxColor + "&showStyle=" + moduleObject.attrs.showStyle +
            "&pageSize=" + pageSize + "&borderWidth=" + borderWidth + "&borderColor=" + borderColor +
            "&borderRadius=" + borderRadius;
         // console.log(moduleObject.attrs.defaultArgments);
        }
        if (moduleType == "MAP_IFRAME") {
          var setUse = moduleObject.attrs.setUse || "location";
          console.log(setUse);
          var equipId = moduleObject.attrs.equipId || "";
          console.log(equipId);
          var mapStyle = moduleObject.attrs.mapStyle;
          var borderWidth = moduleObject.attrs.borderWidth;
          //边框颜色
          var borderColor = getColor(moduleObject.attrs.borderColor, 'transparent');
          var borderRadius = moduleObject.attrs.borderRadius;
          //console.log(borderWidth)
          iframeNode.src = iframeSrc + "?mapStyle=" + mapStyle + "&setUse=" + setUse + "&equipId=" + equipId +
            "&borderWidth=" + borderWidth + "&borderColor=" + borderColor + "&borderRadius=" + borderRadius;
          //iframeNode.src = iframeSrc+"?mapStyle="+moduleObject.attrs.mapStyle;
        }
        if (moduleType == "HISTORY_IFRAME") {
          var keys = JSON.parse(moduleObject.attrs.dataKey);
          var dateRange = moduleObject.attrs.dateRange;
          var borderWidth = moduleObject.attrs.borderWidth;
          var borderRadius = moduleObject.attrs.borderRadius;
          //console.log(moduleObject.attrs);

          //面板背景色
          var bgColor = getColor(moduleObject.attrs.bgColor, 'transparent');
          //边框颜色
          var borderColor = getColor(moduleObject.attrs.borderColor, 'transparent');
          //console.log(borderColor);
          //头部文字色
          var headColor = getColor(moduleObject.attrs.headColor, '111111');
          //xy轴轴线颜色
          var axisColorXY = getColor(moduleObject.attrs.zeroAxisColorX, '111111');
          //xy轴文字颜色，图例文字颜色
          var labelColorXY = getColor(moduleObject.attrs.lableColorX, '111111');
          //分割线颜色
          var splitColor = getColor(moduleObject.attrs.horizontalSplitColor, '995911');
          //滑块颜色
          var sliderColor = getColor(moduleObject.attrs.holdSliderColor, '666666');
          for (var s = 0, len = keys.length; s < len; s++) {
            sensorCodes.push(keys[s]['key']);
          }
          var sensorStr = sensorCodes.join(',');
          var argStr = "?dateRange=" + dateRange + "&sensorCode=" + sensorStr + "&bgColor=" + bgColor +
            "&headColor=" + headColor + "&axisColorXY=" + axisColorXY +
            "&labelColorXY=" + labelColorXY + "&splitColor=" + splitColor + "&sliderColor=" + sliderColor +
            "&borderWidth=" + borderWidth + "&borderColor=" + borderColor +
            "&borderRadius=" + borderRadius;
          iframeNode.src = iframeSrc + argStr;
          //console.log(sensorStr);
        }
        //  iframeNode.setAttribute("scrolling","no");
        iframeNode.setAttribute("frameborder", 0);
      }

      //如果是摄像头
      if (moduleType.indexOf("LIVE_IMAGES") != -1 && typeof(moduleType) != "undefined") {


        var iframeSrc_live = moduleObject.attrs.liveSrc;
        var iframeWidth_live = moduleObject.attrs.width * moduleObject.scale().x;
        var iframeHeight_live = moduleObject.attrs.height * moduleObject.scale().y;
        //删除原有的图片
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        this.layer.draw();
        // so position of textarea will be the sum of positions above:
        var areaPosition_live = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };
        var iframeNode_live = document.createElement('iframe');
        document.getElementById("container").appendChild(iframeNode_live);
        //document.body.appendChild(iframeNode);
        iframeNode_live.className = 'yjzt_HTMLelement_class';
        //70是经测试后的误差纠正
        iframeNode_live.style.height = iframeHeight_live + 70 + 'px';
        iframeNode_live.style.width = iframeWidth_live + 'px';
        iframeNode_live.style.position = 'absolute';
        iframeNode_live.style.top = (areaPosition_live.y - 70) + 'px';
        iframeNode_live.style.left = areaPosition_live.x + 'px';
        iframeNode_live.setAttribute('original_top', areaPosition_live.y - 70);
        iframeNode_live.setAttribute('original_left', areaPosition_live.x);
        while (iframeSrc_live.indexOf("?") != -1) {
          iframeSrc_live = iframeSrc_live.replace("?", "[ask]");
        }
        while (iframeSrc_live.indexOf("&") != -1) {
          iframeSrc_live = iframeSrc_live.replace("&", "[and]");
        }
        while (iframeSrc_live.indexOf("=") != -1) {
          iframeSrc_live = iframeSrc_live.replace("=", "[eq]");
        }
        iframeNode_live.src = "EZUIKit/byzt_live.html?liveSrc=" + iframeSrc_live;
        //  iframeNode.setAttribute("scrolling","no");
        iframeNode_live.setAttribute("frameborder", 0);


      }
      //如果是高级摄像头
      if (moduleType.indexOf("MONITOR_IMAGES") != -1 && typeof(moduleType) != "undefined") {



        var iframeSrc_appKey = moduleObject.attrs.appKey;
        var iframeSrc_appSecret = moduleObject.attrs.appSecret;
        var iframeSrc_deviceSerial = moduleObject.attrs.deviceSerial;
        var iframeSrc_checkCode = moduleObject.attrs.checkCode;
        var videoMode = moduleObject.attrs.videoMode || "standard";
        if (!iframeSrc_appKey || !iframeSrc_appSecret || !iframeSrc_deviceSerial || !iframeSrc_checkCode) {
          layer.msg('高级监控参数缺失！', {
            offset: 't',
            anim: 6,
            icon: 2
          });
        }
        //console.log(videoMode);




        var iframeWidth_live = moduleObject.attrs.width * moduleObject.scale().x;
        var iframeHeight_live = moduleObject.attrs.height * moduleObject.scale().y;


        //删除原有的图片
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        this.layer.draw();


        // so position of textarea will be the sum of positions above:
        var areaPosition_live = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };

        var iframeNode_live = document.createElement('iframe');
        document.getElementById("container").appendChild(iframeNode_live);
        //document.body.appendChild(iframeNode);
        iframeNode_live.className = 'yjzt_echart_class';
        iframeNode_live.style.height = iframeHeight_live + 'px';
        iframeNode_live.style.width = iframeWidth_live + 'px';
        iframeNode_live.style.position = 'absolute';
        iframeNode_live.style.top = areaPosition_live.y + 'px';
        iframeNode_live.style.left = areaPosition_live.x + 'px';
        iframeNode_live.setAttribute('original_top', areaPosition_live.y);
        iframeNode_live.setAttribute('original_left', areaPosition_live.x);
        //iframeNode_live.src = "EZUIKit/camerarun.html?appKey="+iframeSrc_appKey+"&appSecret="+iframeSrc_appSecret+"&deviceSerial="+iframeSrc_deviceSerial+"&checkCode="+iframeSrc_checkCode+"&iframeHeight="+(iframeHeight_live-16);
        //上面为了不出现滚动条而减去16的高度，已通过给camerarun.html加样式解决，无需再减，避免与编辑时不一致；
        iframeNode_live.src = "EZUIKit/camerarun.html?appKey=" + iframeSrc_appKey + "&appSecret=" +
          iframeSrc_appSecret + "&deviceSerial=" + iframeSrc_deviceSerial + "&checkCode=" + iframeSrc_checkCode +
          "&videoMode=" + videoMode + "&iframeHeight=" + (iframeHeight_live);
        //  iframeNode.setAttribute("scrolling","no");
        iframeNode_live.setAttribute("frameborder", 0);



      }
      //如果是视频播放
      if (moduleType.indexOf("SPBF_IMAGES") != -1 && typeof(moduleType) != "undefined") {


        var iframeSrc_live = moduleObject.attrs.liveSrc;

        var iframeWidth_live = moduleObject.attrs.width * moduleObject.scale().x;
        var iframeHeight_live = moduleObject.attrs.height * moduleObject.scale().y;
        if (iframeWidth_live < 261) {
          iframeWidth_live = 261;
        }


        //删除原有的图片
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        this.layer.draw();


        // so position of textarea will be the sum of positions above:
        var areaPosition_live = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };

        var iframeNode_live = document.createElement('iframe');
        document.getElementById("container").appendChild(iframeNode_live);
        //document.body.appendChild(iframeNode);
        iframeNode_live.className = 'yjzt_echart_class';
        iframeNode_live.style.height = iframeHeight_live + 'px';
        iframeNode_live.style.width = iframeWidth_live + 'px';
        iframeNode_live.style.position = 'absolute';
        iframeNode_live.style.top = areaPosition_live.y + 'px';
        iframeNode_live.style.left = areaPosition_live.x + 'px';
        iframeNode_live.src = "vide/byzt_spbf.html?liveSrc=" + iframeSrc_live + "&width=" + iframeWidth_live +
          "&height=" + iframeHeight_live;
        //  iframeNode.setAttribute("scrolling","no");
        iframeNode_live.setAttribute("frameborder", 0);


      }

      //如果是天气
      if (moduleType.indexOf("WEATHER_IMAGES") != -1 && typeof(moduleType) != "undefined") {



        var iframeSrc = moduleObject.attrs.iframeSrc;
        var weatherColor = moduleObject.attrs.weatherColor;
        try {
          weatherColor = "%23" + weatherColor.substr(1, weatherColor.length);
        } catch (e) {
          weatherColor = "%23";
        }
        var iframeWidth_live = moduleObject.attrs.width * moduleObject.scale().x;
        var iframeHeight_live = moduleObject.attrs.height * moduleObject.scale().y;


        //删除原有的图片
        var nodes = moduleObject.find('Image');
        nodes.each(function(node) {
          node.destroy();
        });
        this.layer.draw();


        // so position of textarea will be the sum of positions above:
        var areaPosition_live = {
          x: moduleObject.x(),
          y: moduleObject.y(),
        };

        var iframeNode_WEATHER = document.createElement('iframe');
        document.getElementById("container").appendChild(iframeNode_WEATHER);
        //document.body.appendChild(iframeNode);
        iframeNode_WEATHER.className = 'yjzt_echart_class';
        //iframeNode_WEATHER.style.height =iframeHeight_live+ 'px';
        //iframeNode_WEATHER.style.width =iframeWidth_live+ 'px';
        iframeNode_WEATHER.height = iframeHeight_live;
        iframeNode_WEATHER.width = iframeWidth_live;

        iframeNode_WEATHER.style.position = 'absolute';
        iframeNode_WEATHER.style.top = areaPosition_live.y + 'px';
        iframeNode_WEATHER.style.left = areaPosition_live.x + 'px';
        iframeNode_WEATHER.src = iframeSrc + "&color=" + weatherColor;
        //  iframeNode.setAttribute("scrolling","no");
        iframeNode_WEATHER.setAttribute("frameborder", 0);



      }


    },
    /**
     * 基础信息展示
     * @param moduleObject
     */
    addBasicInfoEvent: function(moduleObject) {
      var basicInfo = moduleObject.attrs.basicInfo; //鼠标悬停基础信息
      var clickInfo = moduleObject.attrs.clickInfo; //点击弹框信息

      if (typeof(basicInfo) != "undefined" && typeof(clickInfo) != "undefined") { // 两个都有效的情况
        var showType = basicInfo.showType;
        var closeViewType = Number(basicInfo.closeViewType) || 0;
        var clickType = clickInfo.clickType;
        if (showType != '' && clickType != '') { //两个都启用的时候
          moduleObject.off('mousemove');
          moduleObject.off('mouseout');
          moduleObject.off('click tap');
          moduleObject.on('mouseover', function() {
            isOver = true;
            document.body.style.cursor = 'pointer';
            if (showType == '1') { //悬停展示
              stageView.showInfo(moduleObject);
              stageView.setInfoData();
            }
          });
          moduleObject.on('mouseout', function(evt) {
            isOver = false;
            document.body.style.cursor = 'default';
            if (closeViewType == 1) {
              layer.closeAll('iframe');
            }
            // 判断鼠标是否在元件的区域内 ，如果不在，则隐藏
            var mousePos = stageView.stage.getPointerPosition();
            var ClientRect = moduleObject.getClientRect();
            var moduleX = moduleObject.x();
            var moduleY = moduleObject.y();
            if (showType == '2') { // 单击展示要计算鼠标区域
              if ((mousePos.x >= moduleX && mousePos.x <= (moduleX + ClientRect.width)) && (mousePos.y >=
                  moduleY && mousePos.y <= (moduleY + ClientRect.height))) {

              } else {
                var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
                groupBasicInfo.hide();
                stageView.layer.draw();
              }
            } else {
              var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
              groupBasicInfo.hide();
              stageView.layer.draw();

            }
          });
          //单击弹框
          moduleObject.on('click tap', function(evt) {
            var urlContent = clickInfo.urlContent; //弹框出现时要展示的url
            var contentWidth = clickInfo.contentWidth; //弹框的宽
            var contentHeight = clickInfo.contentHeight; //弹框的高

            layer.open({
              title: '信息',
              type: 2,
              skin: 'layer-class',
              area: [contentWidth + 'px', contentHeight + 'px'],
              fixed: false, //不固定
              maxmin: true,
              content: urlContent,
              end: function(index, layero) {
                //   关闭弹框后执行的代码
              }
            });

          });
        }
        if (showType != '' && clickType == '') { //基本信息启用，弹框不启用
          moduleObject.off('mousemove');
          moduleObject.off('mouseout');
          moduleObject.on('mouseover', function() {
            isOver = true;
            document.body.style.cursor = 'pointer';
            if (showType == '1') { //悬停展示
              stageView.showInfo(moduleObject);
              stageView.setInfoData();
            }
          });
          moduleObject.on('mouseout', function(evt) {
            isOver = false;
            if (closeViewType == 1) {
              layer.closeAll('iframe');
            }
            document.body.style.cursor = 'default';
            // 判断鼠标是否在元件的区域内 ，如果不在，则隐藏
            var mousePos = stageView.stage.getPointerPosition();
            var ClientRect = moduleObject.getClientRect();
            var moduleX = moduleObject.x();
            var moduleY = moduleObject.y();
            if (showType == '2') { // 单击展示要计算鼠标区域
              if ((mousePos.x >= moduleX && mousePos.x <= (moduleX + ClientRect.width)) && (mousePos.y >=
                  moduleY && mousePos.y <= (moduleY + ClientRect.height))) {

              } else {
                var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
                groupBasicInfo.hide();
                stageView.layer.draw();
              }
            } else {
              var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
              groupBasicInfo.hide();
              stageView.layer.draw();

            }
          });
        }
        if (showType == '' && clickType != '') { //基本信息不启用，弹框启用的时候
          moduleObject.off('mouseover');
          moduleObject.off('mouseout');
          moduleObject.off('click tap');
          moduleObject.on('mousemove', function() {
            document.body.style.cursor = 'pointer';
          });
          moduleObject.on('mouseout', function(evt) {
            document.body.style.cursor = 'default';
          });
          //单击弹框
          moduleObject.on('click tap', function(evt) {
            var urlContent = clickInfo.urlContent; //弹框出现时要展示的url
            var contentWidth = clickInfo.contentWidth; //弹框的宽
            var contentHeight = clickInfo.contentHeight; //弹框的高

            layer.open({
              title: '信息',
              type: 2,
              skin: 'layer-class',
              area: [contentWidth + 'px', contentHeight + 'px'],
              fixed: false, //不固定
              maxmin: true,
              content: urlContent,
              end: function(index, layero) {
                //   关闭弹框后执行的代码
              }
            });

          });
        }

      }
      if (typeof(basicInfo) != "undefined" && typeof(clickInfo) == "undefined") { // 基本信息有效，点击无效的时候
        var showType = basicInfo.showType;
        var closeViewType = Number(basicInfo.closeViewType) || 0;
        if (showType != '') {
          moduleObject.off('mousemove');
          moduleObject.off('mouseout');
          moduleObject.on('mouseover', function() {
            isOver = true;
            document.body.style.cursor = 'pointer';
            if (showType == '1') { //悬停展示
              stageView.showInfo(moduleObject);
              stageView.setInfoData();
            }
          });
          moduleObject.on('mouseout', function(evt) {
            isOver = false;
            if (closeViewType == 1) {
              layer.closeAll('iframe');
            }
            document.body.style.cursor = 'default';
            // 判断鼠标是否在元件的区域内 ，如果不在，则隐藏
            var mousePos = stageView.stage.getPointerPosition();
            var ClientRect = moduleObject.getClientRect();
            var moduleX = moduleObject.x();
            var moduleY = moduleObject.y();
            if (showType == '2') { // 单击展示要计算鼠标区域
              if ((mousePos.x >= moduleX && mousePos.x <= (moduleX + ClientRect.width)) && (mousePos.y >=
                  moduleY && mousePos.y <= (moduleY + ClientRect.height))) {

              } else {
                var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
                groupBasicInfo.hide();
                stageView.layer.draw();
              }
            } else {
              var groupBasicInfo = stageView.layer.find('.groupBasicInfo');
              groupBasicInfo.hide();
              stageView.layer.draw();

            }
          });
        }
      }
      if (typeof(basicInfo) == "undefined" && typeof(clickInfo) != "undefined") { // 基本信息无效，点击有效的时候
        var clickType = clickInfo.clickType;
        if (clickType != '') {
          moduleObject.off('mouseover');
          moduleObject.off('mouseout');
          moduleObject.off('click tap');
          moduleObject.on('mousemove', function() {
            document.body.style.cursor = 'pointer';
          });
          moduleObject.on('mouseout', function(evt) {
            document.body.style.cursor = 'default';
          });
          //单机弹框
          moduleObject.on('click tap', function(evt) {
            var urlContent = clickInfo.urlContent; //弹框出现时要展示的url
            var contentWidth = clickInfo.contentWidth; //弹框的宽
            var contentHeight = clickInfo.contentHeight; //弹框的高
            layer.open({
              title: '信息',
              type: 2,
              skin: 'layer-class',
              area: [contentWidth + 'px', contentHeight + 'px'],
              fixed: false, //不固定
              maxmin: true,
              content: urlContent,
              end: function(index, layero) {
                //   关闭弹框后执行的代码
              }
            });

          });
        }

      }


    },
    setConditionData: function(webSocketData) { //处理条件弹框
      var conditionInfo = stageView.stage.attrs.conditionInfo;
      if (typeof(conditionInfo) != "undefined") { //这个属性纯在时候执行下面的if，以前的画面没有这个属性，所有这样处理。

        var conditionType = conditionInfo.conditionType; //默认为空 空为不启用  1启用
        var conditionWhere = conditionInfo
        .conditionWhere; //conditionWhere: [{devicecode:'',devicename:'',min:'',max:'',urlContent:'http://',contentWidth:'800',contentHeight: '600',time:5000}],//弹框条件

        if (conditionType == '1') {
          for (var i = 0; i < conditionWhere.length; i++) {
            var conditionWhereItem = conditionWhere[i];
            var devicecode = conditionWhereItem.devicecode;
            var min = conditionWhereItem.min;
            var max = conditionWhereItem.max;
            var urlContent = conditionWhereItem.urlContent;
            var contentWidth = conditionWhereItem.contentWidth;
            var contentHeight = conditionWhereItem.contentHeight;
            var time = conditionWhereItem.time;
            var keyValue = webSocketData[devicecode];
            if (typeof(keyValue) != "undefined") {
              if (Number(keyValue) >= Number(min) && Number(keyValue) <= Number(max)) { //条件满足就弹框
                layer.open({
                  title: '信息',
                  time: time * 1000,
                  type: 2,
                  skin: 'layer-class',
                  area: [contentWidth + 'px', contentHeight + 'px'],
                  fixed: false, //不固定
                  maxmin: true,
                  content: urlContent + '? dataPoint=' + devicecode,
                  end: function(index, layero) {
                    //   关闭弹框后执行的代码
                  }
                });
              }

            }



          }

        }

      }
    },
    setInfoData: function(webSocketData) { // 设置基础信息数据
      var webSocketDataTemp;
      if (typeof(webSocketData) == "undefined") {
        try {
          webSocketDataTemp = messageContentTemp;
        } catch (e) {
          webSocketDataTemp = "";
        }

      } else {
        webSocketDataTemp = webSocketData;
      }
      var groupBasicInfo = stageView.layer.find('.groupBasicInfo')[0]; //第一次数据过来，鼠标没有放上去，不会产生该对象
      if (typeof(groupBasicInfo) == "undefined") {
        return;
      }
      var currentModule = groupBasicInfo.attrs.currentModule;
      groupBasicInfo.removeChildren();

      for (var i = 0; i < currentModule.attrs.basicInfo.showContent.length; i++) {
        var dataItem = currentModule.attrs.basicInfo.showContent[i];
        var title = dataItem.title;
        var type = dataItem.type;
        var value = dataItem.value;

        //标题
        var titleText = new Konva.Text({
          x: 0,
          y: i * 25 + 10,
          text: title + " :",
          fontSize: 16,
          fontFamily: '仿宋_GB2312',
          fill: '#33c9ff',
          padding: 10,
          align: 'right',
          // width:100,
          strokeScaleEnabled: false
        });
        //值
        var valueTemp;
        if (type == '1') {
          valueTemp = value;
        }
        if (type == '2') {
          if (webSocketDataTemp == "") {
            valueTemp = '---';
          } else {
            valueTemp = webSocketDataTemp[value.devicecode];
          }

        }
        if (type == '3') {
          if (webSocketDataTemp == "") {
            valueTemp = '---';
          } else {
            valueTemp = new Date().dateFormat('YYYY-mm-dd HH:MM:SS');
          }
        }
        if (type == '4') {
          if (webSocketDataTemp == "") {
            valueTemp = '---';
          } else {
            var currentValue = webSocketDataTemp[value.key.devicecode];
            var stateList = value.state;
            var sfps = 0; // 是否匹配到状态
            for (var j = 0; j < stateList.length; j++) {

              if (currentValue == stateList[j].value) {
                valueTemp = stateList[j].text;
                sfps = 1;
              }

            }
            if (sfps == 0) {
              valueTemp = '状态未匹配';
            }

          }
        }
        if (type == '5') {
          return
        }
        var valueText = new Konva.Text({
          x: titleText.width() - 10,
          y: i * 25 + 10,
          text: valueTemp,
          fontSize: 16,
          fontFamily: '仿宋_GB2312',
          fill: '#ffffff',
          padding: 10,
          align: 'left',
          strokeScaleEnabled: false
        });
        groupBasicInfo.add(titleText);
        groupBasicInfo.add(valueText);



      }

      var ClientRect = groupBasicInfo.getClientRect();
      var backrect = new Konva.Rect({
        x: 0,
        y: 0,
        width: ClientRect.width / this.stage.scale().x,
        height: ClientRect.height / this.stage.scale().y + 15,
        fill: '000000',
        stroke: 'deepskyblue',
        cornerRadius: 4,
        strokeWidth: 4,
        opacity: 0.5
      });
      // console.log(backrect.scale());
      groupBasicInfo.add(backrect);
      // console.log(groupBasicInfo.scale());
      // console.log(this.stage.scale());
      backrect.moveToBottom();
      this.layer.add(groupBasicInfo);
      this.layer.batchDraw();





    },
    showInfo: function(moduleObject) {
      var mousePos = this.stage.getPointerPosition();
      var groupBasicInfo = this.layer.find('.groupBasicInfo'); //删除所有的绘制的区域方
      if (groupBasicInfo.length == 1 && groupBasicInfo[0].id() == moduleObject._id) {
        groupBasicInfo[0].position({
          x: mousePos.x / this.stage.scale().x + 10,
          y: mousePos.y / this.stage.scale().y + 10
        });
        /*groupBasicInfo[0].scale({
            x:this.stage.scaleX(),y:this.stage.scaleY()
        });*/
        groupBasicInfo[0].show();
        this.layer.batchDraw();
      } else {
        groupBasicInfo.destroy();
        var groupInfo = new Konva.Group({
          id: moduleObject._id,
          x: mousePos.x + 10,
          y: mousePos.y + 10,
          // scale:{x:this.stage.scaleX(),y:this.stage.scaleY()},
          name: "groupBasicInfo",
          currentModule: moduleObject
        });

        for (var i = 0; i < moduleObject.attrs.basicInfo.showContent.length; i++) {
          var dataItem = moduleObject.attrs.basicInfo.showContent[i];
          var title = dataItem.title;
          var type = dataItem.type;
          var value = dataItem.value;
          if (type != '5') {
            //标题
            var titleText = new Konva.Text({
              x: 0,
              y: i * 25 + 10,
              text: title + " :",
              fontSize: 16,
              fontFamily: '仿宋_GB2312',
              fill: '#33c9ff',
              padding: 10,
              align: 'right',
              // width:100,
              strokeScaleEnabled: false
            });
          }
          //值
          var valueTemp;
          if (type == '1') {
            valueTemp = value;
          }
          if (type == '2') {
            try {
              if (messageContentTemp == "") {
                valueTemp = '---';
              } else {
                valueTemp = messageContentTemp[value.devicecode];
              }
            } catch (e) {
              valueTemp = '---';
            }
          }
          if (type == '3') {
            try {
              if (messageContentTemp == "") {
                valueTemp = '---';
              } else {
                valueTemp = new Date().dateFormat('YYYY-mm-dd HH:MM:SS');
              }
            } catch (e) {
              valueTemp = '---';
            }
          }
          if (type == '4') {
            try {
              if (messageContentTemp == "") {
                valueTemp = '---';
              } else {
                var currentValue = messageContentTemp[value.key.devicecode];
                var stateList = value.state;
                for (var j = 0; j < stateList.length; j++) {

                  if (currentValue == stateList[j].value) {
                    valueTemp = stateList[j].text;
                  }

                }

              }

            } catch (e) {
              valueTemp = '---';
            }
          }
          if (type == '5') {
            if (hasShow) {
              return
            }
            if (window.location.href.indexOf("preview.html") != -1) { // 说明是预览页面
              layui.layer.msg('预览模式下不能触发该项功能！', {
                offset: 't',
                anim: 6,
                icon: 2
              });
              return;
            }
            var that = this;
            setTimeout(function() {
              //200ms后鼠标还在悬浮，就触发，否则不触发，以避免移动鼠标时误触发
              if (!isOver) {
                return
              }
              var closeViewType = moduleObject.attrs.basicInfo.closeViewType || '0';
              console.log(closeViewType);
              var stageObj = eval("initConfig." + initjson.getStageInfoFunction + "(\"" + value + "\")");
              var stageObjJson = stageObj.draw_params;
              var stageName = stageObj.draw_name;
              localStorage.setItem("stageObjJson", stageObjJson);
              //获取弹框图纸的宽高
              var newWidth = JSON.parse(stageObjJson).attrs.width;
              var newHeight = JSON.parse(stageObjJson).attrs.height;
              var diff = (newWidth / newHeight).toFixed(2);
              //设置修正后弹框图纸的大小
              localStorage.setItem("mouseWidth", newWidth);
              localStorage.setItem("mouseHeight", newHeight);
              localStorage.setItem("mouseDialog", "1");
              //通过母图纸视口设置弹出框大小，减10用以修正避免出现滚动条
              var windowHeight = newHeight
              var windowWidth = newWidth;
              if (newHeight >= Number(localStorage.getItem("fatherHeight"))) {
                windowHeight = Number(localStorage.getItem("fatherHeight")) - 10;
                windowWidth = windowHeight * diff;
                localStorage.setItem("mouseWidth", windowWidth);
                localStorage.setItem("mouseHeight", windowHeight);
              }
              var stageId = value;
              //未解决不能移动的问题
              layer.open({
                //title:[stageName,'color:red'],  //只能写入一个样式
                //title:stageName,  //为空时标题不会显示，也不能拖动
                title: '',
                type: 2,
                skin: 'layer-class',
                //id:"newDialog",
                //如果有标题，高度要加上标题（title）占的高度
                //area:[newWidth+'px',newHeight+44+'px'],
                area: [windowWidth + 'px', windowHeight + 'px'],
                fixed: false, //不固定
                maxmin: false,
                //延时自动关闭
                time: Number(closeViewType) < 10 ? 0 : Number(closeViewType) * 1000,
                //位置top,left
                offset: [newHeight / 2 + 'px', mousePos.x + 10 + 'px'],
                //move:'iframe',
                resize: false, //不允许拉伸
                shade: 0, //不要遮罩层
                zIndex: layer.zIndex,
                content: 'client_view.html?stageId=' + stageId + '&type=dialog',
                //content:"<iframe frameborder='1'  style=width:"+newWidth+"px;height:"+newHeight+"px;margin:0;padding:0;overflow:hidden; src=client_view.html?stageId="+stageId+"&type=dialog></iframe>",
                success: function(layero) {
                  layer.setTop(layero);
                  hasShow = true;
                },
                end: function(index, layero) {
                  localStorage.removeItem("stageObjJson");
                  hasShow = false;

                },
                cancel: function() {
                  localStorage.removeItem("stageObjJson");
                  hasShow = false;
                }
              });

            }, 200)

            return

          }
          var valueText = new Konva.Text({
            x: titleText.width() - 10,
            y: i * 25 + 10,
            text: valueTemp,
            fontSize: 16,
            fontFamily: '仿宋_GB2312',
            fill: '#ffffff',
            padding: 10,
            align: 'left',
            strokeScaleEnabled: false
          });
          groupInfo.add(titleText);
          groupInfo.add(valueText);



        }

        var ClientRect = groupInfo.getClientRect();
        var backrect = new Konva.Rect({
          x: 0,
          y: 0,
          width: ClientRect.width / this.stage.scale().x,
          height: ClientRect.height / this.stage.scale().y + 15,
          fill: '000000',
          stroke: '#0000ff',
          cornerRadius: 4,
          strokeWidth: 4,
          opacity: 0.5
        });
        groupInfo.add(backrect);
        backrect.moveToBottom();
        this.layer.add(groupInfo);
        this.layer.batchDraw();

      }


    },

    addClickEvent: function(moduleObject) {
      var moduleType = moduleObject.attrs.moduleType;
      //只有复位组件会用到timeValue
      var timeValue = parseInt(moduleObject.attrs.timeValue) || 3;
      if (timeValue < 1) {
        timeValue = 1;
      }
      if (timeValue > 120) {
        timeValue = 120;
      }
      //只有复位组件会用到resetType
      var resetType = Number(moduleObject.attrs.resetType) || 1;
      //写值组件判断是否可二次输入
      //console.log(moduleObject.attrs.canSecond);
      var canSecond = Number(moduleObject.attrs.canSecond) || 2;
      //console.log(moduleObject.attrs.confirmText);
      //写值组件获取提示文字的设置
      var confirmText = moduleObject.attrs.confirmText || '';

      var dataKey = "";
      var defaultValue = "";
      try {
        dataKey = eval("(" + moduleObject.attrs.dataKey + ")").key;
        if (typeof(dataKey) == "undefined") { //说明是以前的组件
          dataKey = eval(moduleObject.attrs.dataKey)[0].key;
        }

      } catch (e) {}
      try {
        defaultValue = moduleObject.attrs.defaultValue || 1;
      } catch (e) {

      }
      var clickMethodCall = moduleObject.attrs.clickMethodCall;
      var clickWhere = eval("(" + moduleObject.attrs.clickWhere + ")");
      var clickSignalsWhere = eval("(" + moduleObject.attrs.clickSignalsWhere + ")");
      var targetStage = eval("(" + moduleObject.attrs.jumpTarget + ")"); // 只有跳转画面组件才有
      var readWriteFlag = moduleObject.attrs.readWriteFlag;
      if ((clickMethodCall !== '' && typeof(clickMethodCall) !== "undefined" && ('BUTTON' == moduleType ||
          'BUTTONVALUE' == moduleType || 'BUTTON_JUMP' == moduleType || 'BUTTON_IMPULSES' == moduleType ||
          'RESET' == moduleType)) || (readWriteFlag !== '' && typeof(readWriteFlag) !== "undefined" &&
          readWriteFlag == '2')) {
        //取消事件
        moduleObject.off('mousedown touchstart');
        moduleObject.off('mouseup touchend');
        moduleObject.off('mouseover');
        moduleObject.off('mouseout');
        moduleObject.off('click tap');
        var buttonRect; //形状
        //var buttonText;  //文字
        var backgroundColor;
        try {
          buttonRect = moduleObject.findOne('.buttonRect'); //button的形状
          //buttonText  = moduleObject.findOne('.buttonText'); //button的文字
          backgroundColor = buttonRect.fillLinearGradientColorStops();
        } catch (e) {

        }
        moduleObject.on('mousedown touchstart', function(evt) {

        });
        moduleObject.on('mouseup touchend', function(evt) {


        });
        moduleObject.on('mouseover', function() {
          //buttonText.fill("#fff");设置文字颜色；
          if ('BUTTON' == moduleType || 'BUTTON_JUMP' == moduleType || 'BUTTONVALUE' == moduleType || 'RESET' ==
            moduleType || 'BUTTON_IMPULSES' == moduleType) {
            buttonRect.setShadowBlur(20);
            buttonRect.setShadowOffset(10);
            buttonRect.setShadowColor(backgroundColor[1]);
            buttonRect.setFillLinearGradientColorStops([0, '#00bfff', 0.5, '#ffffff', 1, '#00bfff']);

            // var imageObj= new Image();
            // imageObj.src="test.jpg";
            // imageObj.onload = function() {
            //   buttonRect.fillPatternImage(imageObj);
            // };
            // //image.src = 'path/to/image/jpg';
            // //buttonRect.fillPatternImage(image);
            //    buttonRect.fillPatternOffset({ x:0, y:0 });
            // console.log("a");
          }
          document.body.style.cursor = 'pointer';
          moduleObject.getLayer().draw();
        });
        moduleObject.on('mouseout', function() {
          if ('BUTTON' == moduleType || 'BUTTON_JUMP' == moduleType || 'BUTTONVALUE' == moduleType || 'RESET' ==
            moduleType || 'BUTTON_IMPULSES' == moduleType) {
            buttonRect.setShadowBlur(0);
            buttonRect.setShadowOffset(0);
            //console.log(backgroundColor);
            buttonRect.setFillLinearGradientColorStops(backgroundColor);
          }
          document.body.style.cursor = 'default';
          moduleObject.getLayer().draw();
        });

        moduleObject.on('click tap', function(evt) {

          if ('BUTTON' == moduleType) {
            var changeType = moduleObject.attrs.changeType || "normal";
            var code = clickWhere[0]['code'];
            var content = clickWhere[0]['content'];
            var contentText = content + "CONTROLCMD" + dataKey;
            if (code == '1') { //发送命令
              try {
                if (dataKey == '') {
                  layui.layer.msg('请绑定变量！', {
                    offset: 't',
                    anim: 6,
                    icon: 2
                  });
                } else {
                  eval("webSocketClilent." + clickMethodCall + "('" + contentText + "')");
                }
              } catch (e) {
                layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                  offset: 't',
                  anim: 6,
                  icon: 2
                });
              }
            } else if (code == '2') { //打开链接
              if ($_IsURL(content)) {
                if (changeType == 'normal') {
                  window.open(content, "", "");
                } else {
                  var features =
                    "height=768, width=1366, top=100, left=100, toolbar=no, menubar=no,scrollbars=no,resizable=no, location=no, status=no";
                  window.open(content, "newWindow", features, "replace=true");
                }
                //window.open(content);
              } else {
                layui.layer.msg('该网址不是有效网址', {
                  offset: 't',
                  anim: 6,
                  icon: 2
                });
              }


            } else if (code == 3) {
              if (window.location.href.indexOf("preview.html") != -1) { // 说明是预览页面
                layui.layer.msg('预览模式下不能触发该项功能！', {
                  offset: 't',
                  anim: 6,
                  icon: 2
                });
                return;
              }
              //document.getElementById("mainIframe").src="static/jyzt/client_view.html?stageId="+content;
              //location.href = 'http://' + location.host + location.pathname + '?stageId=' + content;
              //console.log(location.protocol);
              if (changeType == 'normal' || !changeType) {
                window.location.replace(location.protocol + '//' + location.host + location.pathname +
                  '?stageId=' + content);
                localStorage.setItem("stageId", content);
              } else if (changeType == 'newWindow') {
                var stageObj = eval("initConfig." + initjson.getStageInfoFunction + "(\"" + content +
                  "\")");
                var stageObjJson = stageObj.draw_params;
                var stageName = stageObj.draw_name;
                localStorage.setItem("stageObjJson", stageObjJson)
                //获取弹框图纸的宽高
                var newWidth = JSON.parse(stageObjJson).attrs.width;
                var newHeight = JSON.parse(stageObjJson).attrs.height;
                var diff = (newWidth / newHeight).toFixed(2);
                //设置修正后弹框图纸的大小
                localStorage.setItem("newWidth", newWidth);
                localStorage.setItem("newHeight", newHeight);
                //通过母图纸视口设置弹出框大小，减10用以修正避免出现滚动条
                //由于全屏时，对话框关闭图标会被遮挡，所以改为减50；
                //44为对话框标题栏高度
                var windowHeight = newHeight + 44
                var windowWidth = newWidth;
                if ((newHeight + 44) >= Number(localStorage.getItem("viewHeight"))) {
                  windowHeight = Number(localStorage.getItem("viewHeight")) - 50;
                  windowWidth = (windowHeight - 44) * diff;
                  localStorage.setItem("newWidth", windowWidth);
                  localStorage.setItem("newHeight", windowHeight - 44);
                }
                var stageId = content;
                //未解决不能移动的问题
                layer.open({
                  //title:[stageName,'color:red'],  //只能写入一个样式
                  title: stageName, //为空时标题不会显示，也不能拖动
                  type: 2,
                  skin: 'layer-class',
                  //id:"newDialog",
                  //如果有标题，高度要加上标题（title）占的高度
                  area: [windowWidth + 'px', windowHeight + 'px'],
                  fixed: false, //不固定
                  maxmin: false,
                  //move:'iframe',
                  resize: false, //不允许拉伸
                  shade: 0.6,
                  zIndex: layer.zIndex,
                  //content: 'newWindow.html?stageId='+stageId+'&type=dialog',
                  content: 'client_view.html?stageId=' + stageId + '&type=dialog',
                  //content:"<iframe frameborder='1'  style=width:"+newWidth+"px;height:"+newHeight+"px;margin:0;padding:0;overflow:hidden; src=client_view.html?stageId="+stageId+"&type=dialog></iframe>",
                  success: function(layero) {
                    layer.setTop(layero);
                  },
                  end: function(index, layero) {
                    localStorage.removeItem("stageObjJson");
                  },
                  cancel: function() {
                    localStorage.removeItem("stageObjJson");
                  }
                });

                //可移动不完美方案
                // layer.open({
                // 	title:'',
                // 	type: 1,
                // 	//id:"newDialog",
                // 	area:[w+'px',h+'px'],
                // 	fixed:false, //不固定
                // 	maxmin: false,
                // 	move:'iframe',
                // 	resize:true, //不允许拉伸
                // 	shade:0.6,
                // 	zIndex: layer.zIndex,
                // 	//content: 'newWindow.html?stageId='+stageId+'&type=dialog',
                // 	//content:'client_view.html?stageId='+stageId+'&type=dialog',
                // 	content:"<iframe frameborder='1'  style=width:"+newWidth+"px;height:"+newHeight+"px;margin:0;padding:0;overflow:hidden; src=client_view.html?stageId="+stageId+"&type=dialog></iframe>",
                // 	success: function(layero){
                // 	    layer.setTop(layero);
                // 	},
                // 	end: function(index, layero){
                //         localStorage.removeItem("stageObjJson");
                //     },
                // 	cancel:function(){
                // 		localStorage.removeItem("stageObjJson");
                // 	}
                // });

              }

            }

          } else if ('BUTTON_IMPULSES' == moduleType) {

            var start = clickSignalsWhere[0]['start'];
            var time = clickSignalsWhere[0]['time'];
            var end = clickSignalsWhere[0]['end'];
            var contentstart = start + "CONTROLCMD" + dataKey;
            var contentend = end + "CONTROLCMD" + dataKey;

            try {
              if (dataKey == '') {
                layui.layer.msg('请绑定变量！', {
                  offset: 't',
                  anim: 6,
                  icon: 2
                });
              } else {

                layer.confirm('该操作将会先发送命令【' + start + '】,' + time + '秒后再发送命令【' + end + '】,确认是否发送？', {
                  btn: ['确定', '取消'] //按钮
                }, function(index) {
                  eval("webSocketClilent." + clickMethodCall + "('" + contentstart + "')");
                  window.setTimeout(function() {
                    eval("webSocketClilent." + clickMethodCall + "('" + contentend + "')");
                  }, time * 1000);
                  layer.close(index);
                }, function() {});

                //window.clearTimeout(t1);


              }
            } catch (e) {
              layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                offset: 't',
                anim: 6,
                icon: 2
              });
            }


          } else if ('BUTTONVALUE' == moduleType) {
            if (canSecond == 1) {
              var BUTTONVALUE_contentText = defaultValue + "CONTROLCMD" + dataKey + "CONTROLCMD" + "写值" +
                "CONTROLCMD" + confirmText;
              try {
                eval("webSocketClilent." + clickMethodCall + "('" + BUTTONVALUE_contentText + "')");
              } catch (e) {
                layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                  offset: 't',
                  anim: 6,
                  icon: 2
                });
              }
            } else {
              layer.open({
                title: '请输入要设置的值',
                type: 2,
                area: ['452px', '150px'],
                skin: 'layer-class',
                fixed: false, //不固定
                maxmin: false,
                content: 'writeValue.html?defauleValue=' + defaultValue + "&sssjValue=" +
                  messageContentTemp[dataKey],
                end: function(index, layero) {
                  if (stageView.writeValue != '') {
                    var BUTTONVALUE_contentText = stageView.writeValue + "CONTROLCMD" + dataKey +
                      "CONTROLCMD" + "写值" + "CONTROLCMD" + confirmText;
                    try {
                      eval("webSocketClilent." + clickMethodCall + "('" + BUTTONVALUE_contentText + "')");
                    } catch (e) {
                      layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                        offset: 't',
                        anim: 6,
                        icon: 2
                      });
                    }
                    stageView.writeValue = '';
                  }
                }
              });

            }


          } else if ('RESET' == moduleType) {
            try {
              //if(stageView.writeValue!==""){
              var cmds = "CONTROLCMD" + dataKey + "CONTROLCMD" + "复位" + "CONTROLCMD" + timeValue +
                "CONTROLCMD" + resetType;
              // eval("webSocketClilent.sendCmdWebSocket(cmds)");
              eval("webSocketClilent." + clickMethodCall + "('" + cmds + "')");
              // }else{
              //     layui.layer.msg('点击命令未设置，不能触发！', {
              //         offset: 't',
              //         anim: 6,
              //         icon:2
              //     });
              // }

            } catch (e) {
              layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                offset: 't',
                anim: 6,
                icon: 2
              });
            }
          } else if ('BUTTON_JUMP' == moduleType) {
            var targetStageId = targetStage.targetCode;

            var oUrl = window.location.href.toString();
            if (oUrl.indexOf("preview.html") != -1) { // 说明是预览页面
              layui.layer.msg('预览模式下不能触发该项功能！', {
                offset: 't',
                anim: 6,
                icon: 2
              });
            } else {
              // stageId 替换为要跳转的 stageId
              var re = eval('/(stageId=)([^&]*)/gi');
              var nUrl = oUrl.replace(re, 'stageId=' + targetStageId);
              window.location.replace(nUrl)
            }



          } else {
            layer.open({
              title: '请输入要设置的值',
              type: 2,
              area: ['452px', '150px'],
              skin: 'layer-class',
              fixed: false, //不固定
              maxmin: false,
              content: 'writeValue.html?defauleValue=' + defaultValue + "&sssjValue=" + messageContentTemp[
                dataKey],
              end: function(index, layero) {


                if (stageView.writeValue != '') {
                  var else_contentText = stageView.writeValue + "CONTROLCMD" + dataKey;;
                  try {
                    eval("webSocketClilent." + clickMethodCall + "('" + else_contentText + "')");
                  } catch (e) {
                    layui.layer.msg('预览模式下未链接webservice服务端，不能触发！', {
                      offset: 't',
                      anim: 6,
                      icon: 2
                    });
                  }
                  stageView.writeValue = '';
                }



              }

            });

          }


        });
      }
    },

    /**
     * 设置场景数据驱动场景组件动画
     * stageData Json格式
     */
    setStageData: function(stageData) {
      var stageData_ = stageData;
      var groups = this.stage.find('Group');
      this.setInfoData(stageData); // 设置组件基础数据
      //this.setConditionData(stageData);// 处理条件弹框
      //this.stage.draw();
      groups.each(function(group) {
        //数据来源方式
        var dataSourceType = group.attrs.dataSourceType;
        //console.log(dataSourceType);
        if (dataSourceType == "platform") {
          return;
        }
        var dataKey = group.attrs.dataKey;
        var moduleT = group.attrs.moduleType; //组件类型  IMAGES ,STATIC,SVG,
        var methodCall = group.attrs.methodCall; //组件本身要调用的方法
        var rotateMethodCall = group.attrs.rotateMethodCall; //旋转要调用的方法
        var hideMethodCall = group.attrs.hideMethodCall; //隐藏要调用的方法
        var sparklingMethodCall = group.attrs.sparklingMethodCall; //闪烁要调用的方法
        var groupTemp = group;
        if (typeof(rotateMethodCall) != "undefined" && rotateMethodCall !== "") { //旋转
          //console.log("1="+groupTemp);
          moduleAnimation.rotateModule(groupTemp, stageData_);

        }
        if (typeof(hideMethodCall) != "undefined" && hideMethodCall !== "") { //隐藏
          //console.log("2="+groupTemp);
          moduleAnimation.hideModule(groupTemp, stageData_);

        }
        if (typeof(sparklingMethodCall) != "undefined" && sparklingMethodCall !== "") { //闪烁
          //console.log("3="+groupTemp);
          moduleAnimation.sparklingModule(groupTemp, stageData_);

        }

        if (typeof(methodCall) != "undefined" && methodCall !== '') {
          var dataKeyArray = '';
          try {
            dataKeyArray = eval(group.attrs.dataKey);
          } catch (e) {
            dataKeyArray = eval("[" + group.attrs.dataKey + "]"); //兼容之前创建好的画面
          }
          var jsonstr = {};
          if (dataKeyArray && dataKeyArray.length) {
            for (var i = 0; i < dataKeyArray.length; i++) {
              var key = dataKeyArray[i].key;
              if (key === '') {
                return;
              }
              if (typeof(stageData[key]) != 'undefined') {
                jsonstr[key] = stageData[key];
              }
            }

          } else {
            console.log(group);
          }



          if (JSON.stringify(jsonstr) != "{}") {
            // eval("moduleAnimation."+methodCall+"(groupTemp,"+jsonstr+")"); eval 会影响代码混淆

            if (methodCall == "setLineValue") {
              moduleAnimation.setLineValue(groupTemp, jsonstr);
            }
            if (methodCall == "setPoolValue") {
              moduleAnimation.setPoolValue(groupTemp, jsonstr);
            }
            if (methodCall == "setTextValue") {
              moduleAnimation.setTextValue(groupTemp, jsonstr);
            }
            if (methodCall == "setTValue") {
              moduleAnimation.setTValue(groupTemp, jsonstr);
            }
            if (methodCall == "setEchart_GaugeValue") {
              moduleAnimation.setEchart_GaugeValue(groupTemp, jsonstr);
            }
            if (methodCall == "setStatusValue") {
              moduleAnimation.setStatusValue(groupTemp, jsonstr);
            }
            if (methodCall == "setStatusLight") {
              moduleAnimation.setStatusLight(groupTemp, jsonstr);
            }
            if (methodCall == "setStatusLine") {
              moduleAnimation.setStatusLine(groupTemp, jsonstr);
            }
            if (methodCall == "setStatusElectric") {
              moduleAnimation.setStatusElectric(groupTemp, jsonstr);
            }
            if (methodCall == "setSwitchValue") {
              moduleAnimation.setSwitchValue(groupTemp, jsonstr);
            }
            if (methodCall == "setImageStatusValue") {
              moduleAnimation.setImageStatusValue(groupTemp, jsonstr);
            }
            if (methodCall == "rotateModuleNew") {
              moduleAnimation.rotateModuleNew(groupTemp, jsonstr);
            }
            if (methodCall == "setResetLight") {
              moduleAnimation.setResetLight(groupTemp, jsonstr);
            }


          }
        }




        // console.log(1);

      });
      // console.log(2);
      this.stage.batchDraw();



    },
    /**
     * 场景放大缩小，还原
     */
    stageMaxMin: function(type) {

      var xtype = 1;
      var ytype = 1;
      if (type == "max") {
        xtype = this.stage.scale().x + 0.05;
        ytype = this.stage.scale().y + 0.05;
      }
      if (type == "min") {
        xtype = this.stage.scale().x - 0.05;
        ytype = this.stage.scale().y - 0.05;
      }
      if (type == "restore" || xtype == 1) {
        this.stage.position({
          x: 0,
          y: 0
        }); //回复场景原来的位置
        //this.stage.draggable(false);
      }
      /* var layer_background = this.stage.findOne('.layer_background');//背景也要设置，这样才知道原始的场景大小有多大，有个参照
       layer_background.scale({
       x: xtype,
       y: xtype
       });*/
      this.stage.scale({
        x: xtype,
        y: xtype
      });
      this.stage.batchDraw();

      //放大放大缩小画布一起放大缩小
      this.stage.width(this.stage_width_original * this.stage.scale().x);
      this.stage.height(this.stage_height_original * this.stage.scale().y);
      //画面平移需要参数
      var iframeWindow = $("#container").parent(); //窗口大小
      var windowWidth = iframeWindow.width(); //窗口宽
      var windowHeight = iframeWindow.height(); //窗口高

      var canvasDiv = $("#container"); //画布
      var canvasWidth = canvasDiv.width(); //画布宽
      var canvasHeight = canvasDiv.height(); //画布高


      $('#container').unbind('mousedown');
      $('#container').unbind('mousemove');
      $('#container').unbind('mouseup');
      $(document).unbind('mousemove');
      $(document).unbind('mouseup');

      //放大缩小后，画面平移要从新计算
      // $(document).mousemove(function(e) {
      //     if (!!this.move) {
      //         var posix = !document.move_target ? {'x': 0, 'y': 0} : document.move_target.posix,
      //             callback = document.call_down || function() {

      //                 var top_=((e.pageY+(canvasHeight*(stageView.scaling+1))/2)-(canvasHeight/2))-((windowHeight-canvasHeight)/2)-posix.y

      //                 var left_=((e.pageX+(canvasWidth*(stageView.scaling+1))/2)-(canvasWidth/2))-((windowWidth-canvasWidth)/2)-posix.x;

      //                 $(this.move_target).css({
      //                     'top':top_,
      //                     'left':left_
      //                 });

      //             };
      //         callback.call(this, e, posix);
      //     }
      // }).mouseup(function(e) {
      //     if (!!this.move) {
      //         var callback = document.call_up || function(){};
      //         callback.call(this, e);
      //         $.extend(this, {
      //             'move': false,
      //             'move_target': null,
      //             'call_down': false,
      //             'call_up': false
      //         });
      //     }
      // });
      // $('#container').mousedown(function(e) {
      //     var offset = $(this).offset();
      //     this.posix = {'x': e.pageX - offset.left, 'y': e.pageY - offset.top};
      //     $.extend(document, {'move': true, 'move_target': this});
      // });











    }, //添加鼠标滚轮事件
    addMouseListens: function(stageO) {
      var container = stageO.container();

      //先取消滚轮
      container.removeEventListener('DOMMouseScroll', this.scrollFunc);
      container.onmousewheel = null;
      //给页面绑定滑轮滚动事件
      if (document.addEventListener) { //firefox
        container.addEventListener('DOMMouseScroll', this.scrollFunc, false);
      }
      //滚动滑轮触发scrollFunc方法  //ie 谷歌
      container.onmousewheel = container.onmousewheel = this.scrollFunc;

    },
    scrollFunc: function(e) {
      e.preventDefault();
      e = e || window.event;
      if (e.wheelDelta) { //判断浏览器IE，谷歌滑轮事件
        if (e.wheelDelta > 0) { //当滑轮向上滚动时
          stageView.stageMaxMin('max');
        }
        if (e.wheelDelta < 0) { //当滑轮向下滚动时
          stageView.stageMaxMin('min');
        }
      } else if (e.detail) { //Firefox滑轮事件
        if (e.detail > 0) { //当滑轮向上滚动时
          stageView.stageMaxMin('max');
        }
        if (e.detail < 0) { //当滑轮向下滚动时
          stageView.stageMaxMin('min');
        }
      }
    }

  }
  win.StageView = StageView;
}(window);
